Javascript JS:在复杂的父子数组中按字段查找对象
我使用Javascript ES6,但有一个问题 我有一个数组:Javascript JS:在复杂的父子数组中按字段查找对象,javascript,ecmascript-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', c
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,文本:“我想取这个”}
我试过了,但没有成功
var object=commentList.find(o=>o.id==15)
=>未定义
我将把逻辑提取到一个函数中,然后迭代子数组并返回您请求的(第一个匹配)
var commentList=[
{'id':1,文本:'A',子项:[{'id':2,文本:'B'}]},
{'id':4,文本:“asd”,子项:[]},
{'id':5,文本:'vx',子项:[{'id':7,文本:'xxss'}]},
{'id':8,文本:'ghfdh',孩子:[{'id':15,文本:'I want to take this'}]},
{'id':10,文本:'A',子项:[{'id':18,文本:'Bsda'}]},
]
const findChildById=(id,arr)=>{
const result=arr.find(o=>o.id==id)
if(result)返回结果
用于(arr的常数厘米){
const result=cm.children.find(o=>o.id==id)
if(result)返回结果
}
}
log(findChildById(10,commentList))
您可以通过检查id
或获取子项来采用迭代和递归的方法
const find=(数组,id)=>{
var结果;
some(o=>result=o.id==id?o:find(o.children | |[],id));
返回结果;
};
var commentList=[{id:1,文本:'A',子项:[{id:2,文本:'B'}]},{id:4,文本:'asd',子项:[},{id:5,文本:'vx',子项:[{id:7,文本:'xxss'}},{id:8,文本:'ghfdh',子项:[{id:15,文本:'I want to take'asd',}},{10,文本:'A',子项:[{id:18,文本:'Bsda'}];
console.log(find(commentList,15))代码>可用于递归查找项目。如果没有项,函数将返回未定义的:
const find=(数组=[],id)=>{
for(数组的常量项){
const result=item.id==id?item:find(item.children,id);
if(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'},{asd:10,text:'A',children id:18,text:'Bsda'}];
const result=find(commentList,15);
控制台日志(结果)代码>以下非常简单和基本的代码应该适合您。我假设所有数组中所有子元素的所有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;
}
}
}
}
var结果=null;
变量idToSearch=15;
var i=0;
var j=0;
对于(i=0;i=0){
对于(j=0;jCan那些子数组可以任意嵌套还是只有一个级别?查找递归commentList.concat(…commentList.map(o=>o.children)).find(o=>o.id==15)
应该这样做……假设您已经知道您的id属于一个孩子object@Bergi,你是什么意思?OP说他想搜索子数组。如果id不存在,则返回一个自定义字符串。OP从来没有说过他只想搜索子数组,或者他想查找子数组。@Bergi,我明白了,谢谢你的关注。我已经更新了“在家长中查找”和“仅在孩子中查找”的代码。伙计,你太棒了。我已经找了很久了。非常感谢。