javascript 获取递归嵌套值的算法

gojuced7  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(94)

我正在写一个程序,首先必须匹配一个具有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: '' }
// ]
68de4m5k

68de4m5k1#

您可以用一个循环来搜索和构建所有id及其对象的哈希表。
最后,获取结果的最后一个对象,并获取父对象,直到没有更多的父对象可用。

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' }],
    searchValue = 'ventas OUT Personal plus',
    result = [],
    ids = {};

for (const program of programs) {
    if (program.name === searchValue) result.push(program);
    ids[program.id] = program;
}

while (result.at(-1).programParent)
    result.push(ids[result.at(-1).programParent]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关问题