如何将对象存储在数组中? [重复]

问题描述 投票:0回答:2

我有两个数组,我想将它们存储在一个数组中并将它们创建为一个对象。

const name = ["Amy", "Robert", "Sofie"];
const age = ["21", "28", "25"];

我想要的输出是:

const person =[{name: 'Amy', age: '21'}, {name: 'Robert', age: '28'}, {name: 'Sofie', age: '25'}];

有没有一种方法可以使它像这样循环,因为我的数组很长,手动输入它会很麻烦。谢谢。

javascript arrays loops javascript-objects
2个回答
0
投票

鉴于两个数组的长度相同,可以使用

map
函数来实现。

const name = ["Amy", "Robert", "Sofie"];
const age = ["21", "28", "25"];

const person = name.map((nameValue, index) => {
  const ageValue = age[index];
  return { name: nameValue, age: ageValue };
});

console.log(person);


0
投票

你可以像这样使用 Array.map:

const names = ["Amy", "Robert", "Sofie"];
const ages = ["21", "28", "25"];

const persons = names.map((name, i) => ({name, age: ages[i]}));

console.log(persons)

考虑到数组长度必须相等。
并在命名数组时使用plural

© www.soinside.com 2019 - 2024. All rights reserved.