我有一个示例数组
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"}
];
答案 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);