[英]Using nested forEach loops to push and object to an array
I'd love an explanation as to why the result of this function don't match my expectation.我想解释一下为什么这个函数的结果不符合我的期望。
const numbers = [ 1, 2 ]
const objects = [{f: 'a'}, {f: 'b'}]
async function(domain) {
let matrix = []
objects.forEach((object) => {
numbers.forEach((number) => {
object.number = number
matrix.push(object)
})
})
return matrix
}()
The result, once the promise is resolved returns:结果,一旦承诺被解决,就会返回:
[
{ f: 'a', number: 2 },
{ f: 'a', number: 2 },
{ f: 'b', number: 2 },
{ f: 'b', number: 2 }
]
But, my expectation is that it would return:但是,我的期望是它会返回:
[
{ f: 'a', number: 1 },
{ f: 'a', number: 2 },
{ f: 'b', number: 1 },
{ f: 'b', number: 2 }
]
One of the things that puzzles me the most is that if I console.log
the value of object just before I push, it logs out each of the objects in my expected result.最让我困惑的一件事是,如果我在推送之前console.log
对象的值,它会记录我预期结果中的每个对象。
Because objects are passed by reference and you are modifying original object, instead you can push new object.因为对象是通过引用传递的并且您正在修改原始对象,所以您可以推送新对象。
const numbers = [ 1, 2 ] const objects = [{f: 'a'}, {f: 'b'}] let matrix = [] objects.forEach((object) => { numbers.forEach((number) => { matrix.push({...object, number}) }) }) console.log(matrix)
Use Array.flatMap()
to iterate the objects
, with a nested Array.map()
to iterate the numbers
and return an array of new objects with the relevant number.使用Array.flatMap()
迭代objects
,使用嵌套的Array.map()
迭代numbers
并返回具有相关数字的新对象数组。 The flatMap will flatten the arrays produced by the map to a single array: flatMap 会将地图生成的数组展平为单个数组:
const numbers = [ 1, 2 ] const objects = [{f: 'a'}, {f: 'b'}] const matrix = objects.flatMap(o => // map the objects and flatten numbers.map( // map the numbers number => ({ ...o, number }) // return a new object with the number ) ); console.log(matrix);
Old answer:旧答案:
Use nested Array#map to iterate the objects
and the numbers
, and Object#assign to create new objects that include the relevant number.使用嵌套的Array#map迭代objects
和numbers
,使用Object#assign创建包含相关数字的新对象。 Flatten resulting nested arrays by using the spread syntax in Array#concat :使用Array#concat 中的展开语法来展平生成的嵌套数组:
const numbers = [ 1, 2 ] const objects = [{f: 'a'}, {f: 'b'}] const matrix = [].concat(... // flatten the nested arrays objects.map((o) => // map the objects numbers.map( // map the numbers (number) => Object.assign({}, o, { number }) // return a new object with the number ) )); console.log(matrix);
@Nenad is correct. @Nenad是正确的。 You can also do it with reduce and map .您也可以使用reduce和map来做到这一点。
const numbers = [ 1, 2 ]; const objects = [{f: 'a'}, {f: 'b'}]; const matrix = numbers.reduce((acc, nxt) => { const numberedObjs = objects.map(obj => ({...obj, number:nxt})); acc.push(...numberedObjs); return acc; }, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.