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?
Any kind of help will be appreciated.
Thanks
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With