Java脚本函数根据父id从数组返回值

java script function returned value from array by parent id

本文关键字:id 数组 返回值 脚本 函数 Java      更新时间:2023-09-26

我有一个数组var sub_type=[[]];
此数组中的每个元素都是包含3个value (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]

我如何构建一个函数,返回所有(孩子和父母)的id:

function get_parent_child(some_id){code here}

如果我输入id=2,它会返回parent=1 child=4,5

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;
}

如果数组保持这样(Id, Name, ParentId),您可以遍历数组并获得子数组。这将通过parentId创建一个包含你想要的子数组。

可以使用数组过滤器

参见下面的代码片段

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));