如果可能的话,如何使用现有的 JS 库(RxJS for Observables、Lodash/Underscore/whatever)进行转换(无需复杂的 foreach 循环)
以下结构:
{
"result": [
{
"content": {
"resources": [
{
"prop": [
{
"key": "BAR",
"value": "Bar getting better"
},
{
"key": "FOO",
"value": "Foo is cool"
}
]
}
]
}
}
]
}
很容易进入这个吗?
{
"BAR": "Bar getting better",
"FOO": "Foo is cool"
}
最佳答案
在 Lodash 中,使用 _.keyBy
然后_.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>
关于javascript - 使用 TypeScript/JS/RxJS/map/reduce/filter 等将嵌套 JSON 转换为平面 JSON,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38638569/