Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge array of objects with an object using Object.assign

Tags:

ecmascript-6

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

like image 293
Haris Hajdarevic Avatar asked Feb 06 '23 19:02

Haris Hajdarevic


1 Answers

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);
like image 172
CodingIntrigue Avatar answered Jun 06 '23 01:06

CodingIntrigue