Find a value in an array of objects in Javascript

The Solution to Find a value in an array of objects in Javascript is


Finding the array element:

_x000D_
_x000D_
let arr = [_x000D_
    { name:"string 1", value:"this", other: "that" },_x000D_
    { name:"string 2", value:"this", other: "that" }_x000D_
];_x000D_
_x000D_
let obj = arr.find(o => o.name === 'string 1');_x000D_
_x000D_
console.log(obj);
_x000D_
_x000D_
_x000D_


Replacing the array element:

_x000D_
_x000D_
let arr = [_x000D_
    { name:"string 1", value:"this", other: "that" },_x000D_
    { name:"string 2", value:"this", other: "that" }_x000D_
];_x000D_
_x000D_
let obj = arr.find((o, i) => {_x000D_
    if (o.name === 'string 1') {_x000D_
        arr[i] = { name: 'new string', value: 'this', other: 'that' };_x000D_
        return true; // stop searching_x000D_
    }_x000D_
});_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

~ Answered on 2012-09-17 15:24:48


Most Viewed Questions: