Languages
[Edit]
EN

JavaScript - find and update values in array of objects

0 points
Created by:
JoanneSenior
1070

In this article, we would like to show you how to find and update values in an array of objects in JavaScript.

1. Using findIndex() method

In this example, we use findIndex() method to get the index of an element with the same id as the replacement.id and update the element with the replacement object.

// ONLINE-RUNNER:browser;

const array = [
    { id: 1, name: 'a' },
    { id: 2, name: 'b' },
    { id: 3, name: 'c' },
];

const replacement = { id: 3, name: 'd' };

const index = array.findIndex((x) => x.id === replacement.id);

array[index] = replacement;

console.log(JSON.stringify(array));

Note:

This solution will update only the first occurrence of an object with given id (id: 3).

2. Using forEach() method

In this example, we use forEach() method to loop through the array and update all elements whose id is equal to the replacement.id with the replacement object.

// ONLINE-RUNNER:browser;

const array = [
    { id: 1, name: 'a' },
    { id: 2, name: 'b' },
    { id: 3, name: 'c' },
];

const replacement = { id: 3, name: 'd' };

array.forEach((element, index) => {
    if (element.id === replacement.id) {
        array[index] = replacement;
    }
});

console.log(JSON.stringify(array));

Note:

This solution will update all occurrences of objects with given id (id: 3).

 

References

  1. Array.prototype.indexOf() - JavaScript | MDN
  2. Array.prototype.forEach() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join