简体   繁体   中英

converting formatted json object to array of objects by keys

I have a very generic that may be a common case when processing json data to some other format, such as:

json = {
  "Title1": {
    "a1": {
      "key1": "val1",
      "key2": "val2",
      "key3": "val3"
    },
    "a2": {
      "key1": "val1",
      "key2": "val2",
      "key3": {
        "key4": "val4"
      }
    }
  }
}

into a array format such as:

var arr = [{
      "name": "Title1",
      _children: [{
          "name": "a1",
          _children: [{
              "name": "key1",
              "value": "val1"
            },
            {
              "name": "key2",
              "value": "val2"
            },
            {
              "name": "key3",
              "value": "val3"
            }
          ]
        },
        {
          "name": "a2",
          _children: [{
              "name": "key1",
              "value": "val1"
            },
            {
              "name": "key2",
              "value": "val2"
            },
            {
              "name": "key3",
              _children: [{
                "name": "key4",
                "value": "val4"
              }]
            }
          ]
        }
      }
    ]

The logic applies recursively to any bottom level, so the final product will be an array like above.

I cannot think of how to implement this, do you have any suggestion?

Using Object.entries() and recursion

 let json = {"Title1":{"a1":{"key1":"val1","key2":"val2","key3":"val3"},"a2":{"key1":"val1","key2":"val2","key3":{"key4":"val4"}}}} function recur(obj) { return Object.entries(obj).flatMap(([key, val]) => { let o = { name: key } if(typeof val === 'object') o._children = recur(val) else o.value = val return [o] }) } console.log(recur(json)) 

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