Обновление свойства в объекте в массиве JavaScript
var result = foo.map(el => el.bar == 1 ? {...el, baz: [11,22,33]} : el);
Mohamed Mahfouz
var result = foo.map(el => el.bar == 1 ? {...el, baz: [11,22,33]} : el);
//Initailize array of objects.
let myArray = [
{id: 0, name: "Jhon"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
],
//Find index of specific object using findIndex method.
objIndex = myArray.findIndex((obj => obj.id == 1));
//Log object to Console.
console.log("Before update: ", myArray[objIndex])
//Update object's name property.
myArray[objIndex].name = "Laila"
//Log object to console again.
console.log("After update: ", myArray[objIndex])
Run code snippet
//change in array itself without need to another one
arr.map(el =>{ el.bar == 1 && el.baz--} ); // don't forget {} in arrow function
foo.forEach(function(obj) {
if (obj.bar === 1) {
obj.baz[0] = 11;
obj.baz[1] = 22;
obj.baz[2] = 33;
// Or: `obj.baz = [11, 22, 33];`
}
});