前提・実現したいこと
ループ処理中に新しく配列作成をしたいのですが、どうやっても最後の配列の値で構成された配列になってしまいます。
理想の結果の内容になるためにはどうしたらいいかアドバイスをお願いします。
該当のソースコード
const kanas = [ {name: 'ま', id: 'ma'}, {name: 'み', id: 'mi'} ] const kanaRooms = [ {label: '', owner_id: '', admin_id: 2}, {label: '', owner_id: '', admin_id: 3} ] const moge = [] kanas.forEach(function(val) { console.log('val:' + JSON.stringify(val)) const r = Array.from(kanaRooms) console.log('r:' + JSON.stringify(r)) r.forEach(function(val2) { const insert = val2 insert.label = val.name insert.owner_id = val.id moge.push(insert) }) }) console.log(moge)
上記の結果
> "val:{"name":"ま","id":"ma"}" > "r:[{"label":"","owner_id":"","admin_id":2},{"label":"","owner_id":"","admin_id":3}]" > "val:{"name":"み","id":"mi"}" > "r:[{"label":"ま","owner_id":"ma","admin_id":2},{"label":"ま","owner_id":"ma","admin_id":3}]" > Array [Object { label: "み", owner_id: "mi", admin_id: 2 }, Object { label: "み", owner_id: "mi", admin_id: 3 }, Object { label: "み", owner_id: "mi", admin_id: 2 }, Object { label: "み", owner_id: "mi", admin_id: 3 }]
理想の結果
> "val:{"name":"ま","id":"ma"}" > "r:[{"label":"","owner_id":"","admin_id":2},{"label":"","owner_id":"","admin_id":3}]" > "val:{"name":"み","id":"mi"}" > "r:[{"label":"ま","owner_id":"ma","admin_id":2},{"label":"ま","owner_id":"ma","admin_id":3}]" > Array [Object { label: "ま", owner_id: "ma", admin_id: 2 }, Object { label: "ま", owner_id: "ma", admin_id: 3 }, Object { label: "み", owner_id: "mi", admin_id: 2 }, Object { label: "み", owner_id: "mi", admin_id: 3 }]
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。