Underscore _.flatten with prefix of the to be flatten object
-
21-12-2019 - |
Question
I need to flatten an object like this:
{
ProductId: {
Id: "123456-1234-1234-1234-123456789012",
Type: "product",
Name: "Product"
}
}
to look like
{
ProductId_Id: "123456-1234-1234-1234-123456789012",
ProductId_Type: "product",
ProductId_Name: "Product"
}
and I'm currently trying to archive that with underscore, but _.flatten doesn't have have a parameter for that.
Solution
You can you .map and .reduce
var raw = {
ProductId: {
Id: "123456-1234-1234-1234-123456789012",
Type: "product",
Name: "Product"
}
},
flatten = _.map(raw, function(item, k){
return _.reduce(item, function(obj, val, key){
obj[[k,key].join('_')] = val;
return obj;
}, {});
});
console.log(flatten[0])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow