javascript - 使用 TypeScript/JS/RxJS/map/reduce/filter 等将嵌套 JSON 转换为平面 JSON,

标签 javascript json underscore.js lodash data-conversion

如果可能的话,如何使用现有的 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/

相关文章:

javascript - Gruntjs 更改下划线模板分隔符

javascript - 在同一 Angular.js 应用程序中使用 'ui.bootstrap' 和 '720kb.datepicker' 模块时出错

c# - 将具有增量名称的 JSON 对象映射到 C# 模型

json - NetSuite RESTlet 保存的搜索返回限制

javascript - IE 11下划线js语法错误

php - 排序公共(public)属性数组

javascript - 使用 React/Socket.IO 无法读取未定义错误的属性 'emit'

javascript - 另一个 JavaScript 重定向

javascript - 检查 Angular 中 select 中的选项

c# - 将 "/Date(1309498021672)/"反序列化为 DateTime