根据属性值lodash将对象数组中的属性合并到另一个对象中 [英] Merge property from an array of objects into another based on property value lodash

查看:50
本文介绍了根据属性值lodash将对象数组中的属性合并到另一个对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个对象数组,它们每个都有一个共同的 id.我需要将数组 2 的对象的属性添加到对象数组 1,如果它们具有匹配的 ids.

数组 1:

<预><代码>[{编号:1,姓名:汤姆,年龄:24},{编号:2,姓名:蒂姆,年龄:25},{编号:3,姓名:杰克,年龄:24},]

数组 2:

<预><代码>[{编号:1,性别:男,眼睛颜色:蓝色,重量:150},{编号:2,性别:男,眼睛颜色:绿色,重量:175},{编号:3,性别:男,眼睛颜色:淡褐色,重量:200},]

预期结果:

<预><代码>[{编号:1,姓名:汤姆,年龄:24,眼睛颜色:蓝色,},{编号:2,姓名:蒂姆,年龄:25,眼睛颜色:绿色,},{编号:3,姓名:杰克,年龄:24,眼睛颜色:淡褐色,},]

我尝试使用 lodash _.merge 函数,但是当我只想添加 eyeColour 时,我最终将所有属性合并到一个数组中.

解决方案

刚刚注意到 Paul 在我处理我的答案时回答了但我还是会添加我的非常相似的代码:

var getEyeColour = function (el) { return _.pick(el, 'eyeColour');}var out = _.merge(arr1, _.map(arr2, getEyeColour));

演示

I have 2 arrays of objects, they each have an id in common. I need a property from objects of array 2 added to objects array 1, if they have matching ids.

Array 1:

[
    {
        id: 1,
        name: tom,
        age: 24
    },
    {
        id: 2,
        name: tim,
        age: 25
    },
    {
        id: 3,
        name: jack,
        age: 24
    },

]

Array 2:

[
    {
        id: 1,
        gender: male,
        eyeColour: blue,
        weight: 150
    },
    {
        id: 2,
        gender: male,
        eyeColour: green,
        weight: 175
    },
    {
        id: 3,
        gender: male,
        eyeColour: hazel,
        weight: 200
    },

]

Desired Outcome:

[
    {
        id: 1,
        name: tom,
        age: 24,
        eyeColour: blue,
    },
    {
        id: 2,
        name: tim,
        age: 25,
        eyeColour: green,
    },
    {
        id: 3,
        name: jack,
        age: 24,
        eyeColour: hazel,
    },

]

I tried using lodash _.merge function but then I end up with all properties into one array, when I only want eyeColour added.

解决方案

Just noticed Paul answered while I was working on my answer but I'll add my very similar code anyway:

var getEyeColour = function (el) { return _.pick(el, 'eyeColour'); }
var out = _.merge(arr1, _.map(arr2, getEyeColour));

DEMO

这篇关于根据属性值lodash将对象数组中的属性合并到另一个对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆