Reputation: 1575
I'm trying to merge array of objects which with an object using Object.assign()
var state = {
items: [{
id: "Harko",
name: "Haris"
},
{
id: "Benko",
name: "Benjo"
}]
}
var a = {
id: "Benko",
name: "Bengalka"
}
What I tried already:
Object.assign(state.items,a);
Object.assign({}, { items: [state.items,a]);
What I want to get is the following:
{
items: [{
id: "Harko",
name: "Haris"
},
{
id: "Benko",
name: "Bengalka"
}]
}
So I want that Object in var state with id "Benko" to be overwritten by var a, because they have same id.
Is this possible with Object.assign?
Upvotes: 4
Views: 6370
Reputation: 443
In additional to Joseph Connolly answer: You can use mergeWith or assignWith methods from lodash with 3rd argument. Example from lodash docs:
function customizer(objValue, srcValue) {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
}
var object = { 'a': [1], 'b': [2] };
var other = { 'a': [3], 'b': [4] };
_.mergeWith(object, other, customizer);
// => { 'a': [1, 3], 'b': [2, 4] }
Upvotes: 0
Reputation: 945
Lodash merge() worked for my use case:
let v = {foo: [{change: "first", leave: "here"}]}
_.merge(v, {foo: [{change: "second"}]})
Value of v after merge:
{ foo: [{change: "second", leave: "here"}]
Compare to Object.assign() which will replace the first item in the array with the second:
Object.assign(v, {foo: [{change: "second"}]})
Value of v after (leave prop is missing):
{ foo: [{change: "second"}] }
Upvotes: 0
Reputation: 78565
You can't really do that at a top-level using Object.assign
. What you need to do is find the object reference first, then you can use Object.assign
to update it's properties:
const state = {
items: [{
id: "Harko",
name: "Haris"
},
{
id: "Benko",
name: "Benjo"
}]
}
const a = {
id: "Benko",
name: "Bengalka"
}
const foundObject = state.items.find(obj => obj.id === a.id);
Object.assign(foundObject, a);
console.log(state);
Upvotes: 8