How to use map to get an array of objects from a parent array of objects

Advertisements

Hi,

I have this code:

   var itemsdata = [
     {"id":"item1", "assets":[{"id":"size","value":1},{"id":"age","value":14}]},
     {"id":"item2", "assets":[{"id":"size","value":1}]},
     {"id":"item13", "assets":[{"id":"size","value":1}]}
    ];

var itemid = 'item1';

var itemassets = itemsdata.map(d => d.id === itemid ? d.assets : '');

console.log(itemassets); //expected output: [{"id":"size","value":1},{"id":"age","value":14}]

I cant get the expected output with this. I tried variants but no use. What is the right way to do it?

Thank you.

>Solution :

You can filter out the empty strings with filter to filter out the empty strings:

var itemassets = itemsdata.map(d => d.id === itemid ? d.assets : '').filter(d => d !== '');

Full example (using null instead of an empty string):

var itemsdata = [{ "id": "item1", "assets": [{ "id": "size", "value": 1 }, { "id": "age", "value": 14 }] }, { "id": "item2", "assets": [{ "id": "size", "value": 1 }] }, { "id": "item13", "assets": [{ "id": "size", "value": 1 }] } ];
var itemid = 'item1';

var itemassets = itemsdata.filter(d => d.id === itemid).map(d => d.assets);

console.log(itemassets[0]); //expected output: [{"id":"size","value":1},{"id":"age","value":14}]

The first filter iterates over your array and only returns the matched items, then the map returns the desired assets attribute.

This will produce an array of arrays, and you only need to print the first item of it.


Or as a different approach:

var itemsdata = [{ "id": "item1", "assets": [{ "id": "size", "value": 1 }, { "id": "age", "value": 14 }] }, { "id": "item2", "assets": [{ "id": "size", "value": 1 }] }, { "id": "item13", "assets": [{ "id": "size", "value": 1 }] }, { "id": "item99", "assets": [] } ];

var itemid = 'item1';

var itemassets = itemsdata.filter(d => d.id === itemid && d.assets).reduce((acc, d) => [...acc, ...d.assets], []);

console.log(itemassets); //expected output: [{"id":"size","value":1},{"id":"age","value":14}]

With reduce you combine your results in one array

Leave a Reply Cancel reply