【问题标题】:Lodash - Merge object from another array with same key as sub object to main arrayLodash - 将具有与子对象相同键的另一个数组中的对象合并到主数组
【发布时间】:2021-10-16 00:32:56
【问题描述】:
const _ = require('lodash');
const parentDetails = [
    {
        'name': '5003',
        'id': '1'
    },
    {
        'name': '5000',
        'id': '2'
    }
];
const childrenDetails = [
    {
        'cid': '11',
        'Reference': '5003'
    },
    {
        'cid': '22',
        'Reference': '5000'
    }
]; 

使用lodash 库的所需输出:从第二个数组中提取匹配的reference 与第一个数组的name,并将匹配的子详细信息作为对象附加到第一个数组,如下所示。结果不应改变原始数组。

result = [
    {
        'name': '5003',
        'id': '1',
        'childrenDetail' : {
            'cid': '11',
            'Reference': '5003'
        }
    },
    {
        'name': '5000',
        'id': '2',
        'childrenDetail' : {
            'cid': '22',
            'Reference': '5000'
        }
    }
];

【问题讨论】:

  • 我认为您不需要lodash,到目前为止您尝试过什么?
  • result = []; for (const i of parentDetails ) { for (const j of childrenDetails ) { if (i.name === j.reference) { i.childrenDetail = j; result.push(i); } } }
  • 我想要使用 lodash 库获得相同的输出。这是任务的一部分。

标签: javascript arrays lodash


【解决方案1】:

这里是一个使用_.find()的例子

const result = parentDetails.map(elm => {
   const childrenDetail = _.find(childrenDetails, elm2 => elm2.Reference === elm.name);
   if (childrenDetail) return ({...elm, childrenDetail});
});
console.log(result);

您也可以将array.map() 替换为_.map()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多