Changing the key name in an array of objects?

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

ES6 map() method:

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

arrayObj = arrayObj.map(item => {
      return {
        stroke: item.key1,
        key2: item.key2
      };
    });

var i;
for(i = 0; i < arrayObj.length; i++){
    arrayObj[i].stroke = arrayObj[i]['key1'];
    delete arrayObj[i].key1;
}

Tags:

Javascript