0

I have an array of object as below:

let arr = [{
    id: 1,
    name: 'John',
    lastName: 'Smith'
  },
  {
    id: 2,
    name: 'Jill',
    lastName: 'Smith'
  }
];

I want to update an object with id = 1 with some properties from another object.

const obj = {
  id: 1,
  name: 'JOHn1'
}

The expected out is:

[{
    id: 1,
    name: 'JOHn1',
    lastName: 'Smith'
  },
  {
    id: 2,
    name: 'Jill',
    lastName: 'Smith'
  }
]

I tried using Object.assign(), but it does not work. Could anyone please let me know.

arr = Object.assign(arr, obj);

thanks

thanks

1 Answer 1

1

You need to find the entry which you want to use as the assign target first: in this case, you need to query for the entry where id is 1. This can be done by using Array.prototype.find to locate the target, and then do Object.assign() on the target itself.

Since the found object is pass-by-reference, updating the object directly will update its entry in your array of objects directly.

See proof-of-concept below:

const arr = [{
    id: 1,
    name: 'John',
    lastName: 'Smith'
  },
  {
    id: 2,
    name: 'Jill',
    lastName: 'Smith'
  }
];

const obj = {
  id: 1,
  name: 'JOHn1'
};

const foundObj = arr.find(({ id }) => id === obj.id);
if (foundObj) {
  Object.assign(foundObj, obj);
}

console.log(arr);

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

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.