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/

2 Answers 2

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.

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

Comments

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

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.