我正在写一个程序,首先必须匹配一个具有name
=== searchValue
的项,然后递归地需要他的programParent
项。第一个匹配是:{ id: '25', name: 'ventas OUT Personal plus', programParent: '24' }
所以他的父亲是:{ id: '24', name: 'ventas OUT Personal', programParent: '23' }
&他的父代是:{ id: '23', name: 'ventas', programParent: '' }
。空字符串表示最后一个父项。
const programs = [
{ 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' },
]
const searchValue = 'ventas OUT Personal plus'
const filteredPrograms = programs.filter(x => x.name === searchValue)
console.log(filteredPrograms)
const result = []
for (let i = 0; i < filteredPrograms.length; i++) {
for (let j = 0; j < programs.length; j++) {
if (filteredPrograms[i].programParent === programs[j].id) {
result.push(programs[j])
}
}
}
console.log(result)
// const expected = [
// { id: '25', name: 'ventas OUT Personal plus', programParent: '24' },
// { id: '24', name: 'ventas OUT Personal', programParent: '23' },
// { id: '23', name: 'ventas', programParent: '' }
// ]
1条答案
按热度按时间68de4m5k1#
您可以用一个循环来搜索和构建所有
id
及其对象的哈希表。最后,获取结果的最后一个对象,并获取父对象,直到没有更多的父对象可用。