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 specifycustomizer
function e.g. to always replace arraysconsole.log(mergeWith(object2, object1, (ining, source) => { if(isArray(ining)) return ining;}));
– Lukasz 'Severiaan' Grela Commented Dec 17, 2024 at 8:21
1 Answer
Reset to default 4Lodash 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; }
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745271382a4619766.html
评论列表(0条)