我有一个数组
var sub_type=[[]];
此数组中的每个元素都是包含3个值(id,name,parent_id)的行
例如 -
row1 [1,"mobile",0]
row2 [2,"samsung",1]
row3 [3,"sony",1]
row4 [4,"S4",2]
row5 [5,"S5",2]
row6 [6,"C2",3]
row7 [7,"Z3",3]
我如何构建一个返回所有(孩子和父母)的函数的函数,如下所示:
function get_parent_child(some_id){code here}
如果我输入id = 2,则返回parent = 1 child = 4,5
答案 0 :(得分:0)
var mainArray = [[1, "test", 0],
[2, "test1", 1],
[3, "test2", 1],
[4, "test3", 2],
[5, "test4", 2]];
var matchedChilds = getChilds(mainArray, 1);
console.log(matchedChilds);
function getChilds(arr, id){
var childs = [];
for (var i = 0; i < arr.length; i++) {
if(arr[i][0] == id || arr[i][2] == id){
childs.push(arr[i]);
}
}
return childs;
}
&#13;
如果数组保持这样(Id,Name,ParentId),您可以遍历数组并获取子项。这将创建一个包含parentId所需子项的新数组。
一种可行的方法。
答案 1 :(得分:0)
您可以使用Array filter
请参阅下面的代码段
var sub_type = [
[1, "mobile", 0],
[2, "samsung", 1],
[3, "sony", 1],
[4, "S4", 2],
[5, "S5", 2],
[6, "C2", 3],
[7, "Z3", 3]
];
function get_parent_child(some_id) {
var myElement = sub_type.find(function(el) {
return el[0] == some_id;
});
return sub_type.filter(function(el) {
return (el[0] == myElement[2] || el[2] == myElement[0]);
})
}
console.log(get_parent_child(2));
&#13;