1

I have an array of this format:

array [ object{key1: v1, key2: v2}, object{key1: v3, key2: v4} ]

right now, to change the value of each object, where it is key is lets say, key1 to v2, I am looping over each object, like this

for(var i=0;i<array.length;i++){
   array[i][key1] = v2;
}

is there a faster way of doing this? for example is it possible to pass an array instead of i like so

 i= [0,1];
 array[i][key1] = v2;

3 Answers 3

1

One way is using map():

var arr = [ {key1: 'v1', key2: 'v2'}, {key1: 'v3', key2: 'v4'} ];
arr = arr.map(function(x) { x.key1 = 'foo'; return x; });

// arr is now: [ {key1: 'foo', key2: 'v2'}, {key1: 'foo', key2: 'v4'} ];

The above code will change the value corresponding to the key 'key1' of each object in the array.

Sign up to request clarification or add additional context in comments.

3 Comments

lets say the name of the key was stored in some variable (var J) how would I implement this
Then you'd replace x.key1 with x[j] inside map()
It makes no sense at all to use map like that, and moreover it's misleading to anyone reading the code later.
1

is there a faster way of doing this?

Not particularly (certainly the currently accepted answer isn't remotely faster).

You could speed it up slightly by looping backward so you don't have to constantly re-check the length of the array:

for(var i = array.length - 1; i >= 0; i--){
   array[i][key1] = v2;
}

If you meant more concise rather than faster you could use forEach:

array.forEach(function(entry) { entry[key1] = v2; });

...or with an ES2015+ arrow function:

array.forEach(entry => { entry[key1] = v2; });

Or using ES2015+'s for-of (not for-in) loop:

for (const entry of array) {
    entry[key1] = v2;
}

All of those will likely have worse performance than your original. It won't matter in 99.9999999% of use cases. :-)

2 Comments

+1 for the reverse looping for any minute gain if at all (for really huge arrays, it probably will) . Btw, my answer is 5 years old. Now when I look at it, it doesn't make much sense even to me tbh. :)
@techfoobar: LOL :-) I've had that reaction to old answers of mine.
0

Used the following approach :

var arr = [{'key1' : 5, 'key2' : 4},{'key1' : 3, 'key2' : 4}];

arr.map(function(x){ x['key1'] = 20 ;})

console.log(arr);

// output will be [{'key1' : 20, 'key2' : 4},{'key1' : 20, 'key2' : 4}];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.