Dalitos
Dalitos

Reputation: 109

Property of an Object in an Array

i have an array with objects as elements:

var array = [{a:x}, {b:y}, {a:z}]

now i want to add for array[0] and array[2] an extra property

array[0].b = q;
array[2].b = q;

Is it possible to call it shorter?

array[0].b = array[2].b = q

Maybe also shorter then this?

Upvotes: 2

Views: 28

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386728

You could iterate the indices and create the property.

var array = [{ a: 'x' }, {b: 'y' }, { a: 'z' }];

[0, 2].forEach(i => array[i].b = 'q');

console.log(array);

Upvotes: 3

Related Questions