89

How can I change the key name in an array of objects?

var arrayObj = [{key1:'value1', key2:'value2'},{key1:'value1', key2:'value2'}];

How can I change each key1 to stroke so that I get:

var arrayObj = [{stroke:'value1', key2:'value2'},{stroke:'value1', key2:'value2'}];
Paul
  • 139,544
  • 27
  • 275
  • 264
John Cooper
  • 7,343
  • 31
  • 80
  • 100
  • 3
    Here several years later, rather than the [currently-accepted answer](https://stackoverflow.com/a/6809691/157247), you'd use [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) as shown in [this answer](https://stackoverflow.com/a/50951372/157247) and [this one](https://stackoverflow.com/a/53317252/157247) using an arrow function. – T.J. Crowder Feb 28 '19 at 14:18

11 Answers11

90

In recent JavaScript (and TypeScript), use destructuring with rest syntax, spread syntax, and array map to replace one of the key strings in an array of objects.

const arrayOfObj = [{
  key1: 'value1',
  key2: 'value2'
}, {
  key1: 'value1',
  key2: 'value2'
}];
const newArrayOfObj = arrayOfObj.map(({
  key1: stroke,
  ...rest
}) => ({
  stroke,
  ...rest
}));

console.log(newArrayOfObj);
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Marcus
  • 3,459
  • 1
  • 26
  • 25
  • 2
    Spread is optional, It's just there if you want to keep your old values in your array. Nice answer, really neat and powerful nonetheless. – Alex Beugnet Aug 30 '18 at 08:59
  • 1
    How to make "stroke" dynamically passed to map function? – Prashant Mar 31 '20 at 11:25
  • 7
    @Prashant, good question (how to pass 'stroke' dynamically)! Would the following code work for you? ```const newKey = 'stroke'; const newArrayOfObj = arrayOfObj.map(({ key1, ...rest }) => ({ [newKey]: key1, ...rest }));``` – Marcus Mar 31 '20 at 16:10
  • 1
    Note, this doesn't replace anything. It makes a new array with new property names. – jfriend00 Apr 26 '21 at 20:05
  • Is it possible to use this on nested attributes, e.g. const arrayOfObj = [{attributes: { key1: 'value1', key2: 'value2' }}, {attributes: { key1: 'value1', key2: 'value2' }}];? – Jerry Dec 10 '21 at 01:21
49
var i;
for(i = 0; i < arrayObj.length; i++){
    arrayObj[i].stroke = arrayObj[i]['key1'];
    delete arrayObj[i].key1;
}
Paul
  • 139,544
  • 27
  • 275
  • 264
37

ES6 map() method:

let arrayObj = [{key1:'value1', key2:'value2'},{key1:'value1', key2:'value2'}];

arrayObj = arrayObj.map(item => {
  return {
    stroke: item.key1,
    key2: item.key2
  };
});
    
console.log("arrayObj = " + JSON.stringify(arrayObj));
alex351
  • 1,826
  • 1
  • 21
  • 32
  • 2
    But you need to know all the keys in the object and also write each of them in the returning object. – Omkar Sep 25 '19 at 07:03
  • you dont need to know all the keys, you can just use the spread operator like this: var arrayObj = [{key1:'value1', key2:'value2'},{key1:'value1', key2:'value2'}]; arrayObj = arrayObj.map(item => { return { ...item, key2: item.key2 }; }); – Gautam Oct 21 '20 at 00:54
  • but this also keeps the old keys – Dariusz Legizynski Oct 18 '22 at 13:34
  • Don't think so, try running the code snippet. – alex351 Oct 18 '22 at 14:11
19

You can't change a property name, you have to add the value with a new name and delete the old property:

for (var i = 0; i < arrayObj.length; i++) {
  arrayObj[i].stroke = arrayObj[i].key1;
  delete arrayObj[i].key1;
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
17

just one line of code needed with ES6

try following code :

arrayObj.map(({ stroke, key2 }) => ({ yourNewKey: stroke, yourNewKey2: key2 }));
jayesh sheta
  • 181
  • 1
  • 5
6

const company =  [{ id:"1", name:"somename"},{ id:"1", name:"somename"}]

company.map(({ id, name }) => ({ companyId: id, companyName: name }));

// output
//[{ companyId:"1", companyName:"somename"},{ companyId:"1", //companyName:"somename"}]

Ashif Zafar
  • 623
  • 5
  • 6
3

You don't change a key name. You can assign a new key name/value and then remove the previous key if you want. In your example:

var arrayObj = [{key1,'value1', key2:'value2'},{key1,'value1', key2:'value2'}];
var o = arrayObj[0];   // get first object
var val = o.key1;      // get current value
o.stroke = val;        // assign to new key
delete o.key1;         // remove previous key

If you wanted to do that for all the objects in your main array, you would just put that in a loop that iterates over the contents of your array. I've put more intermediate assignments in here than neccessary just to document what's going on.

Or a shortened version in a loop:

for (var i = 0; i < arrayObj.length; i++) {
    var o = arrayObj[i];
    o.stroke = o.key1;
    delete o.key1;
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
2
function changeKey(originalKey, newKey, arr)
{
  var newArr = [];
  for(var i = 0; i < arr.length; i++)
  {
    var obj = arr[i];
    obj[newKey] = obj[originalKey];
    delete(obj[originalKey]);
    newArr.push(obj);
  }
  return newArr;
}
Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
1

pure javascript

var array=[{oldkey:'oldkeyvalue',oldkey2:'oldkey2'}]
var result=array.map(({ oldkey: newkey, ...rest }) => ({ newkey, ...rest }));
console.log(result)

lodash or underscore js

//Lodash/underscore.js
_.map(array,(({ oldkey: newkey, ...rest }))=>({ oldkey: newkey, ...rest }))

The above technique cant set string name

eg:full name or last name

wrong way:

name:full name

right way

name:full_name

you can achieve string object in same way using map

array.map((x)=>{
var y={};
//also use spread operator if necessary but key want to remove manually

y['full name']=x['name'];
return y;
})
Balaji
  • 9,657
  • 5
  • 47
  • 47
0

Another option, when you have other arrays, and they have objects with different keys names and your objects they have equal size.

function convertKeys (arr) {
  const newFormat = arr.map((value) => {
    const arrFormat = Object.values(value)
    return {
      newKey1: arrFormat[0],
      newKey2: arrFormat[1]
    }
  })
}

In array.map, i converted the object to an array and got the values ​​by their index.

  • Welcome to SO. Please explain your answer a little in textual form and tell us, how it works and what makes it different from the other answers given. – ahuemmer Jul 15 '22 at 15:38
-1

You can use an immutable way of changing an object. You can also add new key-value pairs to the object

let arrayOfObj = [{id:"0",name:'myName'},{id:"2",name:'myNewName'}]
const newArr = arrayOfObj.map(item => ({ ...item, id : Number(item.id),someRandomKey:'RandomValue' }))
console.log(newArr)