Vienna Vienna - 4 months ago 59
JSON Question

Converting nested JSON to flat JSON with TypeScript /JS/RxJS / map/reduce/filter whatever,

How can I convert (without complicated foreach loops), if possible with existing JS-Libraries (RxJS for Observables, Lodash/Underscore/whatever)

following structure:

{
"result": [
{
"content": {
"resources": [
{
"prop": [
{
"key": "BAR",
"value": "Bar getting better"
},
{
"key": "FOO",
"value": "Foo is cool"
}
]
}
]
}
}
]
}


into this one easly?

{
"BAR": "Bar getting better",
"FOO": "Foo is cool"
}

Answer

In Lodash, use _.keyBy and then _.mapValues

var data = {"result":[{"content":{"resources":[{"prop":[{"key":"BAR","value":"Bar getting better"},{"key":"FOO","value":"Foo is cool"}]}]}}]},
    input = data.result[0].content.resources[0].prop;

var result = _.mapValues(_.keyBy(input, 'key'), 'value');

console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

Comments