首页 > 解决方案 > 使用 lodash 创建父子关系

问题描述

根据索引值组合 parent 和 chid JSON 数组,并向其添加另一个找到的属性。

数据:比较字段:parentJSON - 索引 childJSON - parent_index

输出: - 父级 - 及其子级 - 父级 - 及其子级

parentJSON:
[{ index:1, name: 'a'}, {index:2, name: 'b'}, {index:3, name: 'c'}, {index:4, name: 'd'}]

childJSON:
[
  { index:1, name: 'aa', parent_index:1}, 
  {index:2, name: 'ab', parent_index:1}, 
  {index:3, name: 'ba', parent_index: 2}, 
  {index:4, name: 'bb', parent_index: 2}, 
  {index:5, name: 'ca', parent_index: 3}, 
  {index:6, name: 'ad', parent_index: 1}
]

output:
[
  { index:1, name: 'a'},
  { index:1, name: 'aa', parent_index:1, found: true}, 
  { index:2, name: 'ab', parent_index:1, found: true},
  { index:6, name: 'ad', parent_index:1, found: true},
  { index:2, name: 'b'},
  { index:3, name: 'ba', parent_index:2, found: true}, 
  { index:4, name: 'bb', parent_index:2, found: true},
  { index:3, name: 'c'},
  { index:5, name: 'ca', parent_index:3, found: true},
  { index:4, name: 'd'},
]

Plunker 链接

标签: javascriptecmascript-6lodash

解决方案


由于您使用的是lodash,因此我的解决方案将全部使用 lodash。

解决此问题的步骤将是:

  1. 是映射childJSON,检查其父索引是否存在

  2. 将两个 json 数组合并为一个。

  3. 按升序对它们进行name排序。

用代码写这个将是:

var childJSON = [
  { index:1, name: 'aa', parent_index:1}, 
  {index:2, name: 'ab', parent_index:1}, 
  {index:3, name: 'ba', parent_index: 2}, 
  {index:4, name: 'bb', parent_index: 2}, 
  {index:5, name: 'ca', parent_index: 3}, 
  {index:6, name: 'ad', parent_index: 1}
];

var parentJSON = [
   { index:1, name: 'a'},
   {index:2, name: 'b'}, 
   {index:3, name: 'c'}, 
   {index:4, name: 'd'}
   ];


childJSON = _.map(childJSON, function(child) {
    child.found = !!_.find(parentJSON, {index: child.parent_index});
    return child;
});

var newArray = _.concat(childJSON, parentJSON);
newArray = _.sortBy(newArray, ['name']);

console.log(newArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>


推荐阅读