0

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?

2
  • Can you please add expected output? Commented Feb 21, 2022 at 22:50
  • @RoMilton I added it as a comment. It should be a string of all the name values; Commented Feb 21, 2022 at 22:54

1 Answer 1

2

You don’t need lodash, it can be done using .reduce() and .map()

const list = [
  {id: 1, Item: []},
  {id: 2, Item: [{name: 'name1'}]},
  {id: 3, Item: [{name: 'name2'}, {name: 'name3'}]},
  {id: 4, Item: []}
];

const getNames = (arr) => {
  const names = arr.reduce((acc, {Item})=>[
     ...acc,
     ...Item.map(({name})=> name)
  ], []);
  return names.join(', ');
}

console.log(getNames(list));

Some feedback on your code: you have conflicting objects called list - it's a global variable, an argument of getNames() and a locally scoped variable inside that function. The _.forEach iterates through an empty locally scoped variable instead of the argument. Be careful of conflicting variable names 😊

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

2 Comments

Or map and flat list.map(el => el.Item).flat().map(el => el.name).join(', ')
Thank you @Ro Milton! Your answer and feedback were really helpful!

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.