Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string values from array in object that is in an array

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 ?

like image 211
Gutelaunetyp Avatar asked Dec 06 '25 22:12

Gutelaunetyp


2 Answers

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);
like image 191
Mamun Avatar answered Dec 08 '25 11:12

Mamun


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);
like image 35
Nikhil Aggarwal Avatar answered Dec 08 '25 12:12

Nikhil Aggarwal