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}
]
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);

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];
});

Comments

1

const writeable =[
[{id: 1, name: "item1", write: true}],
[{id: 3, name: "item3", write: true}]
];

let result = writeable.flat();

console.log(result);

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.