es6重命名对象数组中的键

时间:2018-05-10 06:44:05

标签: javascript

我有一个示例数组

const countries = [
    {"id": 1, "name": "Afghanistan"},
    {"id": 2, "name": "Albania"},
    {"id": 3, "name": "Algeria"},
    {"id": 4, "name": "American Samoa"}
];

如何在es6中将密钥从 id 名称更改为标签

const countries = [
    {"label": 1, "value": "Afghanistan"},
    {"label": 2, "value": "Albania"},
    {"label": 3, "value": "Algeria"},
    {"label": 4, "value": "American Samoa"}
];

1 个答案:

答案 0 :(得分:10)

使用.map将一个数组转换为另一个数组,并解析参数以获得最少的语法噪声:

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

如果您愿意,也可以转换为参数本身中的新属性名称:

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