Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify object property in an array of objects

var foo = [{ bar: 1, baz: [1,2,3] }, { bar: 2, baz: [4,5,6] }];  var filtered = $.grep(foo, function(v){     return v.bar === 1; });  console.log(filtered); 

http://jsfiddle.net/98EsQ/

Is there any way to modify a certain objects property (like the one I'm filtering out above) without creating new arrays and/or objects?

Desired result: [{ bar: 1, baz: [11,22,33] }, { bar: 2, baz: [4,5,6] }]

like image 420
Johan Avatar asked May 22 '13 12:05

Johan


People also ask

How do I change an object's value in an array of objects?

To change the value of an object in an array:Call the findIndex() method to get the index of the specific object. Access the array at the index and change the property's value using dot notation. The value of the object in the array will get updated in place.

How do you modify an object property?

After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.

Can you modify elements in an array?

To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

How do you add a property to an array of objects?

We can use the forEach method to loop through each element in an object and add a property to each. We have the arr array. Then we call forEach with a callback that has the element parameter with the object being iterated through and we assign the b property to a value.


1 Answers

.map with spread (...) operator

var result = foo.map(el => el.bar == 1 ? {...el, baz: [11,22,33]} : el);

like image 194
Piotrek Avatar answered Sep 24 '22 14:09

Piotrek