Katie Katie - 5 months ago 9
Javascript Question

Transforming array of objects using Lodash

I'm trying to simplify a convoluted structure.

I've simplified it as much as I can and have reduced it to this:

[
{'Cells':{'Results':[
{'Key':'ID','Value':123},
{'Key':'Color','Value':'Red'},
{'Key':'Direction','Value':'West'}
]}},
{'Cells':{'Results':[
{'Key':'ID','Value':456},
{'Key':'Color','Value':'Green'},
{'Key':'Direction','Value':'East'}
]}}
]


My lodash is skills are lacking and I need help turning the above into this:

[
{'ID':123, 'Color':'Red', 'Direction':'West'},
{'ID':456, 'Color':'Green', 'Direction':'East'}
]





I should note that the number of keys vary by object by the way. At a minimum, it could have just the ID, but some might have more than those three in the example.

Answer

A solution using Lodash:

var result = _.chain(data)
    .map('Cells.Results')
    .map(res => _.zipObject(_.map(res,"Key"), _.map(res,"Value")))
    .value();