0

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/

Community
  • 1
  • 1
DeseaseSparta
  • 271
  • 2
  • 4
  • 12

2 Answers2

3

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.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
1

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;
    }
  }
}
Stefano Nardo
  • 1,567
  • 2
  • 13
  • 23