I currently have an array of arrays that looks like the following:
const writeable = [
[{id: 1, name: "item1", write: true}],
[{id: 3, name: "item3", write: true}]
]
I would like to convert the array of arrays (all of which contain a single object) to an array of objects.
I have tried mapping through the writeable array and pushing each item into a new array, but because .map returns a new array, I'm left with the same result. Is there a way to do this, or is this not possible?
The expected output:
const newArray = [
{id: 1, name: "item1", write: true},
{id: 3, name: "item3", write: true}
]
Unmitigated
91.5k12 gold badges103 silver badges109 bronze badges
asked Aug 10, 2020 at 17:01
Rob Terrell
2,5574 gold badges22 silver badges48 bronze badges
3 Answers 3
Just use Array#flat.
const writeable = [
[{id: 1, name: "item1", write: true}],
[{id: 3, name: "item3", write: true}]
]
const res = writeable.flat();//default depth is 1
console.log(res);
answered Aug 10, 2020 at 17:07
Unmitigated
91.5k12 gold badges103 silver badges109 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You need to return the object inside the element you are iterating
writeable.map(function (item) {
return item[0];
});
Comments
const writeable =[
[{id: 1, name: "item1", write: true}],
[{id: 3, name: "item3", write: true}]
];
let result = writeable.flat();
console.log(result);
answered Aug 10, 2020 at 17:06
Sascha A.
4,6463 gold badges17 silver badges34 bronze badges
2 Comments
EugenSunic
overkill, just use .flat()
Sascha A.
yes you are right. I thought too complicated. Editted it.
lang-js
.flatMapinstead of.map. Or justwriteable.flat():-)[].concat(...writeable)