我有两个数组,我想将它们存储在一个数组中并将它们创建为一个对象。
const name = ["Amy", "Robert", "Sofie"]; const age = ["21", "28", "25"];
我想要的输出是:
const person =[{name: 'Amy', age: '21'}, {name: 'Robert', age: '28'}, {name: 'Sofie', age: '25'}];
有没有一种方法可以循环它使其成为这样,因为我的数组很长,手动输入它会很麻烦。谢谢。
P粉0806439752024-04-03 17:40:08
由于两个数组的长度相同,可以使用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);
P粉8271215582024-04-03 12:35:13
您可以像这样使用 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)