Kit*_*Kit 6 javascript ecmascript-6
我使用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' }] },
]
Run Code Online (Sandbox Code Playgroud)
这是一个具有父子结构的数组。{'id': 15, text: 'I want to take this' }如果我只有ID,如何获得 Exactly 对象
我尝试过但没成功
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));Run Code Online (Sandbox Code Playgroud)
您可以使用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);Run Code Online (Sandbox Code Playgroud)
我会将逻辑提取到一个函数中,然后迭代子数组并返回您请求的数组(第一个匹配项)。
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))Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7345 次 |
| 最近记录: |