John John -4 years ago 212
Javascript Question

Using lodash to extract the leafs of a mixed object/array

var a = {
{"smart_meter":["The smart meter field is required."],"reading":["The selected reading is invalid."]}
{"invalid_character":["Invalid character in forname.", "Blah blah."]}

I have a object returns from an API, i need to extract the end values to create a single string. The intended output from above owuld be:

The smart meter field is required. The selected reading is invalid.Invalid character in forname. Blah blah.

I know i can build a series of loops to achieve this, but is there is a lodash way? Something along the lines of ?

Answer Source

It's a little ridiculous looking but it works:

var flattenStrings = _.flatMap(_.flatMap(a.errors), function (i) { 
    return _.flatMap(i); 

_.join(flattenStrings, ' ')


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download