javascript - 基于条件的数组中的两种搜索方式 - javascript

标签 javascript arrays

我有 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/

相关文章:

arrays - 以自定义格式显示字符串数组

javascript - Angular 2 编译失败

javascript - 无法发布对象的 javascript 数组

javascript - poptrox 添加可点击的链接/按钮

java - 反转数组中的元素

javascript - 一个对象包含一个对象集合 - 每个对象都有一个 id 和名称,我如何将它们分开?

javascript - 我如何在 HTMLPurifier 中允许脚本、对象、参数、嵌入和 iframe 标签?

javascript - 直接从文件工作时出现 "Unsafe JavaScript attempt to access frame"

java - 如何搜索 2D 字符串数组 - Java

javascript - Array.fill 与赋值时的文字 2D 定义不同