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'}];
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, ...
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.
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.
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);
var i; for(i = 0; i < arrayObj.length; i++){ arrayObj[i].stroke = arrayObj[i]['key1']; delete arrayObj[i].key1; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With