如何使用打字稿将JSON转换为键值字典?

问题描述 投票:0回答:1

我有以下json示例:

{
    "MyTest:": [{
            "main": {
                "name": "Hello"
            },
            "test2": {
                "test3": {
                    "test4": "World"
                },
                "test5": 5
            }
        },
        {
            "main": {
                "name": "Hola"
            },
            "test6": [{
                    "name": "one"
                },
                {
                    "name": "two"
                }
            ]
        }
    ]
}

我正在尝试将其转换为具有键值的数组的数组

[[main.name: "Hello",test2.test3.test4: "World", test2.test5: 5] , 
[main.name = "Hola", test6.name: "one", test6.name: "two"] ];

正在寻找某些功能,例如“ is leaf”-所以我会知道这是值。

任何有关深度迭代的建议都会非常有用。

javascript json typescript loops lodash
1个回答
1
投票
flattenObject()函数将返回一个级别的对象,该对象具有从所有子键构建的键。递归函数检查当前值是否为对象。如果是,则使用_.flatMap()迭代对象,并使用到目前为止收集的键在每个属性上调用自身。如果该值不是对象,则返回具有单个属性(连接的键)和值的对象。

然后将{key:value}个对象的数组合并为一个对象。

const flattenObject = val => { const inner = (val, keys = []) => _.isObject(val) ? // if it's an object or array _.flatMap(val, (v, k) => inner(v, [...keys, k])) // iterate it and call fn with the value and the collected keys : { [keys.join('.')]: val } // return the joined keys with the value return _.merge({}, ...inner(val)) } const obj = {"MyTest":[{"main":{"name":"Hello"},"test2":{"test3":{"test4":"World"},"test5":5}},{"main":{"name":"Hola"},"test6":[{"name":"one"},{"name":"two"}]}]} const result = obj.MyTest.map(flattenObject) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.