我有兩個數組,我想將它們儲存在一個數組中並將它們創建為一個物件。
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)