I have a deeply nested array (list) of objects. Each object has an array, that can be empty or can contain another object. I need to map through them and output a result that will represent a string made from the values of the names of each item.
The result should be ‘name 1, name 2, name 3’.
So far I have this and I am definitely not getting what I need:
const list = [
{id: 1, Item: []},
{id: 2, Item: [{name: 'name1'}]},
{id: 3, Item: [{name: 'name2'}, {name: 'name3'}]},
{id: 4, Item: []}
];
const getNames = (list) => {
const list = [];
_.forEach(list, (child) => {
list.push(child.Item);
});
const filteredList = list.filter(value => JSON.stringify(value) !== '[]');
const mappedList = _.map(filteredList, (el) => {
return el.name;
});
return _.join(mappedList, ', ');
};
const result= getNames(list);
//expected output: 'name 1, name 2, name 3' (string)
Any ideas?