The following code in JavaScript:
const mixedObjects = [1,2,3].map(num => {
return { a: 'always same' }
});
returns the following result:
[
{a: 'always same'},
{a: 'always same'},
{a: 'always same'}
]
I want to return the following without declaring an empty array outside and then pushing into it. So do it all inside the map. Is this possible?
What I want to return:
[
{a: 'always same'},
{b: 1},
{a: 'always same'},
{b: 2},
{a: 'always same'},
{b: 3}
]
CodePudding user response:
Use Array.flatMap()
, and return a tuple of the 2 objects on each iteration. The flatMap would create a flattened array of objects.
const mixedObjects = [1,2,3].flatMap(b => {
return [{ a: 'always same' }, { b }]
});
console.log(mixedObjects);
CodePudding user response:
You can combine map
and flat
methods:
const mixedObjects = [1,2,3].map(num => {
return [{ a: 'always same' }, {b: num}];
}).flat();
P. S. Or use flatMap
method as suggested by Ori Drori.
CodePudding user response:
... reduce
based solutions work as well ...
console.log(
[1,2,3].reduce((result, b) =>
[...result, { a: 'always same' }, { b }] , []
)
);
console.log(
[1,2,3].reduce((result, b) =>
result.concat({ a: 'always same' }, { b }), []
)
);
console.log(
[1,2,3].reduce((result, b) => {
result.push({ a: 'always same' }, { b });
return result;
}, [])
);
.as-console-wrapper { min-height: 100%!important; top: 0; }