Search code examples
ecmascript-6

Merge array of objects with an object using Object.assign


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?


Solution

  • 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);