I have a sample array
const countries = [
{"id": 1, "name": "Afghanistan"},
{"id": 2, "name": "Albania"},
{"id": 3, "name": "Algeria"},
{"id": 4, "name": "American Samoa"}
];
How can i change the keys from id and name to label and value like this in es6?
const countries = [
{"label": 1, "value": "Afghanistan"},
{"label": 2, "value": "Albania"},
{"label": 3, "value": "Algeria"},
{"label": 4, "value": "American Samoa"}
];
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.
Syntax: obj['New key'] = obj['old key']; Note: Renaming the object by simple assignment of variable could be applied on multiple key, value pairs.
Use .map
to transform one array into another, and destructure the arguments for the least syntax noise:
const countries = [
{"id": 1, "name": "Afghanistan"},
{"id": 2, "name": "Albania"},
{"id": 3, "name": "Algeria"},
{"id": 4, "name": "American Samoa"}
];
const transformed = countries.map(({ id, name }) => ({ label: id, value: name }));
console.log(transformed);
You could also transform to the new property names in the arguments themselves, if you wanted:
const countries = [
{"id": 1, "name": "Afghanistan"},
{"id": 2, "name": "Albania"},
{"id": 3, "name": "Algeria"},
{"id": 4, "name": "American Samoa"}
];
const transformed = countries.map(({ id: label, name: value }) => ({ label, value }));
console.log(transformed);
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