John John - 3 months ago 18
Javascript Question

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

var a = {
"errors":{
"meters.electric":[
{"smart_meter":["The smart meter field is required."],"reading":["The selected reading is invalid."]}
],
"forename":[
{"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 https://lodash.com/docs#flattenDeep ?

Joe Joe
Answer

It's a little ridiculous looking but it works:

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

_.join(flattenStrings, ' ')

Example