Reputation: 3
I need convert Array of Array of Objects into a simple Array of objects using JavaScript
Below i go put the current code with the current output
const result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
const a = result.map(item => {
return Object.assign({}, ...item)
})
console.log(a)
Output of the above code (current and wrong output)
[ { "name": "2" }, { "name": "4" }, { "name": "5" }, { "name": "6" } ]
The expected and needed output
[
{
name: '1'
},
{
name: '2'
},
{
name: '3'
},
{
name: '4'
},
{
name: '5'
},
{
name: '6'
}
]
Upvotes: 0
Views: 86
Reputation: 44087
There's a simple and well-supported way to flatten arrays without using flat
- use reduce
and push
(not concat
for efficiency).
const result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
const a = result.reduce((acc, curr) => (acc.push(...curr), acc));
console.log(a);
.as-console-wrapper { max-height: 100% !important; top: auto; }
ES5 syntax:
var result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
var a = result.reduce(function(acc, curr) {
return (Array.prototype.push.apply(acc, curr), acc);
});
console.log(a);
Upvotes: 1
Reputation: 3408
You could use Array.prototype.concat to merge the arrays.
const result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
const b = Array.prototype.concat.apply([], result);
console.log(b);
Upvotes: 0