0

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
7
  • 3
    please add the wanted result. Commented Aug 10, 2020 at 17:03
  • 3
    You'd need to use .flatMap instead of .map. Or just writeable.flat() :-) Commented Aug 10, 2020 at 17:03
  • [].concat.apply([], writeable) Commented Aug 10, 2020 at 17:04
  • Or even [].concat(...writeable) Commented Aug 10, 2020 at 17:04
  • Please share the expected output Commented Aug 10, 2020 at 17:05

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

3

You need to return the object inside the element you are iterating

writeable.map(function (item) {
 return item[0];
});
answered Aug 10, 2020 at 17:06

Comments

1

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

2 Comments

overkill, just use .flat()
yes you are right. I thought too complicated. Editted it.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.