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] }]
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.
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.
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.
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.
.map
with spread (...
) operator
var result = foo.map(el => el.bar == 1 ? {...el, baz: [11,22,33]} : el);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With