简体   繁体   中英

Javascript array, modify values for all keys

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;

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.

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. :-)

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}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM