Ashy Ashcsi
Ashy Ashcsi

Reputation: 1597

Override an object from array of objects in javascript

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

Upvotes: 0

Views: 531

Answers (1)

Terry
Terry

Reputation: 66123

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

Upvotes: 1

Related Questions