我使用了 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
,该如何获取对象{'id': 15, text: 'I want to take this' }
的确切位置
我尝试了但没用
var object = commentList.find(o => o.id === 15)
=> undefined
答案 0 :(得分:2)
您可以通过检查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));
答案 1 :(得分:1)
我将逻辑提取到一个函数中,然后遍历children数组并返回您请求的数组(第一个匹配项)。
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' }] },
]
const findChildById = (id, arr) => {
const result = arr.find(o => o.id === id)
if (result) return result
for (const cm of arr) {
const result = cm.children.find(o => o.id === id)
if (result) return result
}
}
console.log(findChildById(10, commentList))
答案 2 :(得分:1)
您可以使用for...of
来递归查找内容。如果没有项目,该函数将返回未定义的内容:
const find = (array = [], id) => {
for (const item of array) {
const result = item.id === id ? item : find(item.children, id);
if(result) return result;
}
};
const 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' }] }];
const result = find(commentList, 15);
console.log(result);
答案 3 :(得分:1)
遵循非常简单和基本的代码将为您工作。我假设所有数组中所有子元素的所有id是唯一的。这段代码将找到与我们要查找的ID相匹配的第一个元素;
var result = null;
var idToSearch = 15;
var i=0;
var j=0;
for(i=0; i<commentList.length; i++){
var currentChildren = commentList[i].children;
if(currentChildren && currentChildren.length > 0){
for(j=0; j<currentChildren.length; j++){
if(currentChildren[j].id === idToSearch){
result=currentChildren[j];
j=currentChildren.length;
i=commentList.length;
}
}
}
}