开发者

Filter and find properties in array of objects

This code is working but i would like to make it with array methods. The condition of filtering is: if programParent is empty string -> must pass, if id equals to some programParent -> must pass. I was trying to make it with filter method and find, but i need some help. Thanks in advance.

let programsRes = [
    { id: '23', name: 'ventas', programParent: '' },
    { id: '24', name: 'ventas OUT Personal', programParent: '23' },
    { id: '25', name: 'ventas OUT Personal plus', programParent: '24' },
    { id: '26', name: 'ventas IN Hogares', programParent: '23' },
    { id: '27', name: 'Ad Hoc', programParent: '' },
    { id: '28', name: 'Ad Hoc asd', programParent: '27' },
    { id: '29', name: 'Ad Hoc 123', programParent: '27' },
    { id: '30', name: 'ventas IN Personal plus', programParent: '26' },
]   

let expected = [
    { id: '23', name: 'ventas', programParent: '' },
    { id: '24', name: 'ventas OUT Personal', programParent: '23' },
    { id: '26', name: 'ventas IN Hogares', prog开发者_开发技巧ramParent: '23' },
    { id: '27', name: 'Ad Hoc', programParent: '' },
]


let result = []
for (let i = 0; i < programsRes.length; i++) {
    for (let j = 0; j < programsRes.length; j++) {
        if (programsRes[i].programParent === '') {
            result.push(programsRes[i])
            break;
        }
        if (programsRes[i].id === programsRes[j].programParent) {         
            result.push(programsRes[i])  
            break;
        }
    }
}
console.log(result)


let programsRes = [
    { id: '23', name: 'ventas', programParent: '' },
    { id: '24', name: 'ventas OUT Personal', programParent: '23' },
    { id: '25', name: 'ventas OUT Personal plus', programParent: '24' },
    { id: '26', name: 'ventas IN Hogares', programParent: '23' },
    { id: '27', name: 'Ad Hoc', programParent: '' },
    { id: '28', name: 'Ad Hoc asd', programParent: '27' },
    { id: '29', name: 'Ad Hoc 123', programParent: '27' },
    { id: '30', name: 'ventas IN Personal plus', programParent: '26' },
];


let result = programsRes.filter(program => 
            program.programParent === '' || 
            programsRes.some(item => item.programParent === program.id));
console.log(result)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜