Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the key name in an array of objects?

Tags:

javascript

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'}]; 
like image 854
John Cooper Avatar asked Jul 24 '11 20:07

John Cooper


People also ask

How do you change the key of an array of objects?

To change the key name in an array of objects with JavaScript, we use the array map method. const arrayOfObj = [ { key1: "value1", key2: "value2", }, { key1: "value1", key2: "value2", }, ]; const newArrayOfObj = arrayOfObj. map(({ key1: stroke, ... rest }) => ({ stroke, ...

How do you change the particular key value from an array of objects in JavaScript?

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. Spread is optional, It's just there if you want to keep your old values in your array.

How do you rename an object key?

To rename a key in an object:Use bracket notation to assign the value of the old key to the new key. Use the delete operator to delete the old key. The object will contain only the key with the new name.


2 Answers

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);
like image 66
Marcus Avatar answered Oct 07 '22 01:10

Marcus


var i; for(i = 0; i < arrayObj.length; i++){     arrayObj[i].stroke = arrayObj[i]['key1'];     delete arrayObj[i].key1; } 
like image 27
Paul Avatar answered Oct 07 '22 02:10

Paul