简体   繁体   中英

How to convert JSON to a key-value dictionary using typescript?

I have the following json example:

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

I'm trying to convert it to an array of arrays with key-values

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

Looking for some function like "is leaf" - so I will know that is the value.

Any advise for deep iteration will be very appriciated.

The flattenObject() function returns an object of one level, with the keys built from all sub keys. The recursive function checks if the current value is an object. If it is, it iterates the object with _.flatMap() and calls itself on each property with the keys collected so far. If the value is not an object, it returns an object with a single property (the joined keys), and the value.

It then merges the array of { key: value } objects to a single object.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM