yariv bar
yariv bar

Reputation: 976

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"}
    ]
 }

Upvotes: 3

Views: 14535

Answers (2)

Just code
Just code

Reputation: 13801

You can use flatMap, get props and get the desire result like this using lodash.

var data= [{
   superObjectName: "someName",
   subObject: [
      {subObjectName: "someSubName"},
      {subObjectName: "someSubName2"}
    ]
 }];

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

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Upvotes: 2

iofjuupasli
iofjuupasli

Reputation: 3873

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.

Upvotes: 4

Related Questions