DeseaseSparta
DeseaseSparta

Reputation: 271

Replace key in an array of object

I have an array of objects :

arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}]

I have the name of the key I want to replace in my array :

var keyString = 'key1';

And I have the new name the key should take :

var newKey    = 'newKey'

How to make my array this :

arrayOfObject = [{'newKey': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}]

JavaScript: Object Rename Key this can help me to rename the key but the thing is how to access the object first in my array that has the key1 key.

Note that keyString is random. So it's pointless to get it like arrayOfObject[0]

https://jsfiddle.net/tcatsx6e/

Upvotes: 0

Views: 2366

Answers (2)

Stefano Nardo
Stefano Nardo

Reputation: 1647

This will return the index of the object you want to modify.

function(arr, keyString) {
  for (var i = 0; i < arr.length; ++i) {
    if (arr[i][keyString] !== undefined) {
      return i;
    }
  }
}

Upvotes: 1

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19060

Check this solution:

var arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}];

var keyString = 'key1';
var newKey    = 'newKey';

var newArray = arrayOfObject.map(function(item) {
  if (keyString in item) {
    var mem = item[keyString];
    delete item[keyString];
    item[newKey] = mem;
  }
});

Please check this jsbin for a complete example.

Upvotes: 3

Related Questions