Changing value of a property of items in an object array

Just curious to know if there is a better way of doing this.

Say I had a collection/array of javascript objects and wanted to set the value of a specific property of all of the contained objects to the same value. I know i can iterate through the collection/array, and set item[i].propierty= value. I could ES5 and above i could use, so I dont have to write a for loop. But what I wondered if this could be done more efficiently some obscure method? something like collection.children.setProp(prop, value)?

thank as always :slight_smile:

Under the hood, any such method is going to come down to doing the iteration and setting the property. It’s just a question of how pretty it looks from the outside.

ha. I suspected as much. Thanks, m_hutley.

I know that .map() will work on an array. Does it work with collections?


^ _ ^

That type of syntax was being used for several things to keep Java developers happy, but is in the process of being replaced by easier and simpler techniques.

When you have an array of items, use the forEach method to loop through that array.
Use map when you want to create a new modified array of those items.

In this case, using forEach is sensible where you can use arrow-notation to mutate the property of each item.

collection.forEach(o => o.prop = value);

In ES5 notation, the same is achieved with:

collection.forEach(function (o) {
    o.prop = value;
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.