2
\$\begingroup\$

I don't like how transforming the data requires a bunch of nested functions. It's not very readable. Is there a more readable way to do the same transformations in Lodash?

var templates = {
  "fullRenderV80": {
    "stuff": "stuff",
    "screenshots": [
      {
        "device": "iPhone 6",
        "position": 1
      },
      {
        "device": "Watch",
        "position": 2
      }
    ]
  },
  "fullRenderV70": {
    "stuff": "stuff",
    "screenshots": [
      {
        "device": "iPhone 6",
        "position": 1
      },
      {
        "device": "iPad",
        "position": 2
      }
    ]
  }
}

var transformedData = _.groupBy(_.map(templates, 'screenshots'), function(screenshotsArray) {
  return _.reduce(screenshotsArray, function(templateDevicesName, screenshot) {
    return templateDevicesName.concat(screenshot.device)
  }, []).join(' + ')
})

// transformedData is this:
//{
//  "iPhone 6 + Watch": [
//    [
//      {
//        "device": "iPhone 6",
//        "position": 1
//      },
//      {
//        "device": "Watch",
//        "position": 2
//      }
//    ]
//  ],
//  "iPhone 6 + iPad": [
//    [
//      {
//        "device": "iPhone 6",
//        "position": 1
//      },
//      {
//        "device": "iPad",
//        "position": 2
//      }
//    ]
//  ]
//}
\$\endgroup\$
1
\$\begingroup\$

Take advantage of lodash's _() wrapper function, which wraps a value, and allows chaining of methods.

function grouper(screenshotsArray){
  return _.reduce(screenshotsArray, function(templateDevicesName, screenshot) {
    return templateDevicesName + ' + ' + screenshot.device;
  }, '');
}

var transformedData = _(templates).map('screenshots').groupBy(grouper).value();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.