我有 2 个数组 A 和 B:
"A": [{
"name": "test1",
"id": "build:jenkins>test1"
}, {
"name": "test2",
"id": "build:jenkins>test2"
}, {
"name": "maven",
"id": "build:maven"
}, {
"name": "maven1",
"id": "build:maven1"
}]
"B": [{
"name": "jenkins",
"id": "build:jenkins"
}, {
"name": "m1",
"id": "build:maven>m1"
}, {
"name": "m2",
"id": "build:maven>m2"
}, {
"name": "maven3",
"id": "build:maven3"
}]
我正在尝试获取结果数组“C”,它将根据“id”在两个数组中搜索可用的子项,并给出一个数组:
"C":
[{ "id": "build:jenkins",
"children":
[{"name": "test1","id": "build:jenkins>test1"},
{"name": "test2","id": "build:jenkins>test2"}
]
},
{ "id": "build:maven",
"children":
[{"name": "m1","id": "build:maven>m1"},
{"name": "m2","id": "build:maven>m2"}
]
},
{"id": "build:maven1","children":[]},
{"id": "build:maven3","children":[]}
]
我试图迭代数组 A,然后迭代数组 B 以根据 id 找到子项,但无法同时在两个数组中进行双向搜索。请帮我得到像数组C这样的结果。
最佳答案
首先,您需要一个实用函数,可以通过 id
查找数组项:
function findArrayItemById(id, inArray) {
var sep = '>'; // change this if you need another separator, can also be regex
for (var i = 0; i < inArray.length; i++) {
if (inArray[i].id === id.split(sep)[0])
return inArray[i];
}
return false;
}
然后是一个将多个数组合并为一个的函数,采用您需要的格式:
function buildMergedArray(arrays) {
var result = [],
sep = '>', // change this if you need another separator, can also be regex
found;
for (var i = 0; i < arrays.length; i++) {
for (var j = 0; j < arrays[i].length; j++) {
found = findArrayItemById(arrays[i][j].id, result);
if (found)
found.children.push(arrays[i][j]);
else
result.push({
id: arrays[i][j].id.split('>')[0],
children: []
});
}
}
return result;
}
最后,您将获得所需的 C
结果,如下所示:
var result = buildMergedArray([source.A, source.B]);
关于javascript - 基于条件的数组中的两种搜索方式 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34343273/