Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading