Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

javascript - Merge property from an array of objects into another based on property value lodash

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Lodash remains a highly useful bag of utilities, but with the advent of ES6 some of its use cases are less compelling.

For each object (person) in the first array, find the object in the second array with matching ID (see function findPerson). Then merge the two.

function update(array1, array2) {
  var findPerson = id => array2.find(person => person.id === id);

  array1.forEach(person => Object.assign(person, findPerson(person.id));
}

For non-ES6 environments, rewrite arrow functions using traditional syntax. If Array#find is not available, write your own or use some equivalent. For Object.assign, if you prefer use your own equivalent such as _.extend.

This will merge all properties from array2 into array1. To only merge eyeColour:

function update(array1, array2) {
  var findPerson = id => array2.find(person => person.id === id);

  array1.forEach(person => {
    var person2 = findPerson(person.id));
    var {eyeColour} = person2;
    Object.assign(person, {eyeColour});
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...