-3

I want to convert an array from this:

const categories = [{
  name: 'category1',
  items: [
    {itemId: 1, name: 'Item1'},
    {itemId: 2, name: 'Item2'},
  ],
}, {
  name: 'category2',
  items: [
    {itemId: 3, name: 'Item3'},
    {itemId: 4, name: 'Item4'},
  ],
}];

to look something like this:

const result = [ 
  { itemId: 1, name: 'Item1' }, 
  { itemId: 2, name: 'Item2' }, 
  { itemId: 3, name: 'Item3' }, 
  { itemId: 4, name: 'Item4' },
];

Any helps would be amazing! Thank you.

3

2 Answers 2

1

If you're in a environment that supports nodejs over 11.0.0

You can use this piece of code:

categories.flatMap(({items}) => items)

Check the compatibility here

But if you're not in this kind of environment you could use this piece of code:

const result = []
const categories = [ { name: "category1"
        , items: 
          [ { itemId: 1, name: "Item1" } 
          , { itemId: 2, name: "Item2" } 
          ] 
        } 
      , { name: "category2"
        , items: 
          [ { itemId: 3, name: "Item3" } 
          , { itemId: 4, name: "Item4" } 
      ] } ]
categories.map(({items}) => items).forEach(arr => result.push(...arr))
Sign up to request clarification or add additional context in comments.

Comments

0

Try this.

categories.reduce((result, item) => {
  result.push(...item.items);
  return result;
}, []); 

Comments

Your Answer

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.