admin管理员组

文章数量:1417691

I have two objects with some mon keys but different values like below.

const object1 = { 
  name: 'John',
  age: 23,
  books: ['book1', 'book2']
};

const object2 = { 
  name: 'John',
  age: 23,
  books: ['book3'],
  city: 'London'
};

I need the desired output as follows

object3 = { 
  name: 'John',
  age: 23,
  books: ['book3'],
  city: 'London'
};

When I do the merge using lodash as below

object3 = _.merge(object1 , object2);

the output I am getting is

const object3 = { 
  name: 'John',
  age: 23,
  books: ['book1','book2','book3'],
  city: 'London'
};

How can I replace the books array with the new data from object2?

I have two objects with some mon keys but different values like below.

const object1 = { 
  name: 'John',
  age: 23,
  books: ['book1', 'book2']
};

const object2 = { 
  name: 'John',
  age: 23,
  books: ['book3'],
  city: 'London'
};

I need the desired output as follows

object3 = { 
  name: 'John',
  age: 23,
  books: ['book3'],
  city: 'London'
};

When I do the merge using lodash as below

object3 = _.merge(object1 , object2);

the output I am getting is

const object3 = { 
  name: 'John',
  age: 23,
  books: ['book1','book2','book3'],
  city: 'London'
};

How can I replace the books array with the new data from object2?

Share Improve this question edited Feb 14, 2023 at 5:04 user10518298 asked Feb 14, 2023 at 4:57 user10518298user10518298 1994 silver badges19 bronze badges 1
  • For others: There is also a mergeWith where you have option to specify customizer function e.g. to always replace arrays console.log(mergeWith(object2, object1, (ining, source) => { if(isArray(ining)) return ining;})); – Lukasz 'Severiaan' Grela Commented Dec 17, 2024 at 8:21
Add a ment  | 

1 Answer 1

Reset to default 4

Lodash is trying to be helpful by recursively merging subobjects

This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

https://lodash./docs/4.17.15#merge (emphasis mine)

If you don't want this to happen, just use the standard ES6 spread operator ... or Object.assign

const object1 = { 
  name: 'John',
  age: 23,
  books: ['book1', 'book2']
};

const object2 = { 
  name: 'John',
  age: 23,
  books: ['book3'],
  city: 'London'
};

object3 = {...object1, ...object2};
object4 = Object.assign({}, object1, object2);

console.log(object3);
console.log(object4);
/* make the Stack Overflow console bigger */ .as-console-wrapper { max-height: 100vh !important; }

本文标签: javascriptLodash merge two objects but replace the same key values with new object valueStack Overflow