Search code examples
javascriptlodash

Flatten nested objects using Lodash


I'm looping over object with a property set to array, which i then use in the following way:

  let merged= [];
  for (let sup of superObject) {
    let sname = sup.superObjectName;
    for (let sub of sup.subObject) {
      merged.push({superObject: sname, subObject: sub.subObjectName})
    }
  }

Now the code above works and get job done but i feel it can be improved using Lodash and i cant get it to work. i tried using flatMap in few different ways but none seem to work, and the one in the right direction in terms of functionality wont seem like an improvement at all. Any ideas?

UPDATE: superObject example:

{
   superObjectName: "someName",
   subObject: [
      {subObjectName: "someSubName"},
      {subObjectName: "someSubName2"}
    ]
 }

Solution

  • This does the same as your code:

    const merged = _.flatMap(superObject, ({superObjectName, subObject}) =>
        _.map(subObject, ({subObjectName}) => ({
            superObject: superObjectName,
            subObject: subObjectName
        }))
    );
    

    Each value in superObject transformed to Array with map, and then flattened inside flatMap.