3

I have the following JSON object:

var test = {
  data: [{
      itemID: 0,
      categories: [{
        id: 0,
        type: 'a',
        name: 'world'
      }, {
        id: 1,
        type: 'b',
        name: 'plants'
      }]
    },
    {
      itemID: 1,
      categories: [{
        id: 2,
        type: 'w',
        name: 'cars'
      }, {
        id: 3,
        type: 't',
        name: 'bicycles'
      }]
    }

  ]

};
console.log([].concat
.apply([],  test.data.map(item => item.categories.map(el => el.type))));

What I want to do is, to get all types in an array. So the result should look like this:

['a', 'b', 'w', 't']

What I did:

[].concat
.apply([],  test.data.map(item => item.categories.map(el => el.type)))

I have the feeling that this could be done easier.

Does someone know a better solution ?

2 Answers 2

3

You can use Array.prototype.map() and Array.prototype.flat():

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Where depth is Optional

The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

var test = {
  data: [{
      itemID: 0,
      categories: [{
        id: 0,
        type: 'a',
        name: 'world'
      }, {
        id: 1,
        type: 'b',
        name: 'plants'
      }]
    },
    {
      itemID: 1,
      categories: [{
        id: 2,
        type: 'w',
        name: 'cars'
      }, {
        id: 3,
        type: 't',
        name: 'bicycles'
      }]
    }

  ]

};

var type = test.data.map(item => item.categories.map(el => el.type)).flat();
console.log(type);

Sign up to request clarification or add additional context in comments.

Comments

2

Use Array.reduce

var test = {data: [{itemID: 0,categories: [{id: 0,type: 'a',name: 'world'}, {id: 1,type: 'b',name: 'plants'}]},{itemID: 1,categories: [{id: 2,type: 'w',name: 'cars'}, {id: 3,type: 't',name: 'bicycles'}]}]};

let result = test.data.reduce((a,c) => a.concat(c.categories.map(v => v.type)), []);
console.log(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.