Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 rename keys in object array

Tags:

javascript

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"}
];
like image 451
Chukwuemeka Ihedoro Avatar asked May 10 '18 06:05

Chukwuemeka Ihedoro


People also ask

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

How do I rename an object key?

Syntax: obj['New key'] = obj['old key']; Note: Renaming the object by simple assignment of variable could be applied on multiple key, value pairs.


1 Answers

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);
like image 192
CertainPerformance Avatar answered Oct 19 '22 07:10

CertainPerformance