【发布时间】:2020-07-24 22:51:49
【问题描述】:
我目前正在手动循环遍历一个数组并进行越来越深的嵌套循环来比较值,但我很好奇是否有任何方法可以自动执行此搜索?我需要找到深层嵌套数组,比较 1 或 2 个值,然后还可以修改这些值。
示例数组。
searchableArray = [];
searchableArray.push({id: 3, type: 'some-type', text: 'text', nestedElements: [{id: 4, type: 'some-type', text: 'other text', nestedElements: []}, {id: 5, type: 'another-type', text: 'more text', nestedElements: []}]})
searchableArray.push({id: 6, type: 'other-type', text: 'text', nestedElements: [{id: 7, type: 'other-type', text: 'other text', nestedElements: []}, {id: 8, type: 'another-type', text: 'more text', nestedElements: []}]})
searchableArray.push({id: 9, type: 'another-type', text: 'text', nestedElements: [{id: 10, type: 'another-type', text: 'other text', nestedElements: []}, {id: 11, type: 'another-type', text: 'more text', nestedElements: []}]})
基本上我需要搜索 id(它将在整个数组和对象中是唯一的,但可以嵌套在另一个数组内的对象深处的各个级别。但总是称为“nestedElements”。
我需要能够找到 ID,然后修改 ID 所属的对象并将其放回我正在使用的数组中。
现在我只是为每个潜在的嵌套数组制作手动循环。 (这是很多额外的复制粘贴代码)
for(var i = 0; i < searchableArray.length; ++i)
{
if(searchableArray[i].id == 6) //6 would actually be a variable, just doing a manual example
{
if(searchableArray[i].nestedElements.length > 0)
{
for(var j = 0; j < searchableArray[i].nestedElements.length; ++j)
{
if(searchableArray[i].nestedElements[j].id == '7')
{
if(searchableArray[i].nestedElements[j].type == 'other-type')
{
searchableArray[i].nestedElements[j].dosomething = 'do this to something in the object';
}
else if(searchableArray[i].nestedElements[j].type == 'another-type')
{
searchableArray[i].nestedElements[j].dosomething = 'do this other thing to the object';
}
}
}
}
}
}
如果所有内容都使用嵌套循环,这将变得非常庞大,那么有没有更简单的方法来做到这一点?
谢谢!
【问题讨论】:
-
我建议使用递归来解决这个问题
标签: javascript arrays loops object