Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Mapping (modifying) a deeply nested structure of arrays and objects

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 😊

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!