-
mapメソッドを使用する方法:
const names = ["John", "Jane", "Mike"]; const ages = [25, 30, 35]; const cities = ["Tokyo", "Osaka", "Kyoto"]; const people = names.map((name, index) => { return { name: name, age: ages[index], city: cities[index] }; }); console.log(people);
出力:
[ { name: 'John', age: 25, city: 'Tokyo' }, { name: 'Jane', age: 30, city: 'Osaka' }, { name: 'Mike', age: 35, city: 'Kyoto' } ]
-
forループを使用する方法:
const names = ["John", "Jane", "Mike"]; const ages = [25, 30, 35]; const cities = ["Tokyo", "Osaka", "Kyoto"]; const people = []; for (let i = 0; i < names.length; i++) { const person = { name: names[i], age: ages[i], city: cities[i] }; people.push(person); } console.log(people);
出力:
[ { name: 'John', age: 25, city: 'Tokyo' }, { name: 'Jane', age: 30, city: 'Osaka' }, { name: 'Mike', age: 35, city: 'Kyoto' } ]
-
reduceメソッドを使用する方法:
const names = ["John", "Jane", "Mike"]; const ages = [25, 30, 35]; const cities = ["Tokyo", "Osaka", "Kyoto"]; const people = names.reduce((acc, name, index) => { acc.push({ name: name, age: ages[index], city: cities[index] }); return acc; }, []); console.log(people);
出力:
[ { name: 'John', age: 25, city: 'Tokyo' }, { name: 'Jane', age: 30, city: 'Osaka' }, { name: 'Mike', age: 35, city: 'Kyoto' } ]
これらの方法を使用すると、複数の配列からオブジェクトの配列を効果的に作成できます。それぞれの方法は異なるアプローチを取っていますが、同じ結果を得ることができます。必要に応じて、これらの例を参考にしてコードを調整してください。