如何使用以下两个数组:
const age = [31,53,62]
const names = ['john', 'sam', 'kathy']
并将它们格式化为以下内容:
const data = {
"children": [
{ "id": 1,
"name": "john",
"age": 31,
},
{ "id": 2,
"name": "sam",
"age": 53,
},
{ "id": 3,
"name": "kathy",
"age": 62,
}
]
}
答案 0 :(得分:2)
您可以使用array#map
生成对象数组。您可以使用索引来映射名称与年龄。
const age = [31,53,62],
names = ['john', 'sam', 'kathy'],
result = {children: age.map((a,i) => ({id: i+1, name: names[i], age: a}))};
console.log(result);