Home > Enterprise >  Mapping (modifying) a deeply nested structure of arrays and objects
Mapping (modifying) a deeply nested structure of arrays and objects

Time:02-22

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?

CodePudding user response:

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

  • Related