4

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?

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

0

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"}] }

Comments

0

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] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.