gpt4 book ai didi

javascript - JS : Find object by field in a complex Parent-Child Array

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:39:24 24 4
gpt4 key购买 nike

我使用 Javascript ES6 但遇到了问题。

我有一个数组:

var commentList = [
{'id': 1, text: 'A', children: [{'id': 2, text: 'B' }] },
{'id': 4, text: 'asd', children: [] },
{'id': 5, text: 'vx', children: [{'id': 7, text: 'xxss' }] },
{'id': 8, text: 'ghfdh', children: [{'id': 15, text: 'I want to take this' }] },
{'id': 10, text: 'A', children: [{'id': 18, text: 'Bsda' }] },
]

这是一个具有父子结构的数组。如果我只有 ID only

,我怎样才能得到 Exactly object {'id': 15, text: 'I want to take this' }

我试过但没用

var object = commentList.find(o => o.id === 15) => undefined

最佳答案

您可以通过检查 id 或获取子项来采用迭代和递归方法。

const find = (array, id) => {
var result;
array.some(o => result = o.id === id ? o : find(o.children || [], id));
return result;
};

var commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: [] }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];

console.log(find(commentList, 15));

关于javascript - JS : Find object by field in a complex Parent-Child Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com