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]
asked Mar 17, 2016 at 14:26
DeseaseSparta
2812 gold badges4 silver badges13 bronze badges
2 Answers 2
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.
answered Mar 17, 2016 at 14:40
Dmitri Pavlutin
19.2k8 gold badges42 silver badges46 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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;
}
}
}
answered Mar 17, 2016 at 14:32
Stefano Nardo
1,6753 gold badges14 silver badges23 bronze badges
Comments
lang-js