简体   繁体   中英

convert deep nested array of object into plain tab separated string

i have three-level or more nested JSON I need to convert it into nice looking string

for example

let a = {
    "spec":[
        {'key': 'General', 'values': [
            {'key': 'Model Number', 'value': 'REDMI'},
            {'key': 'Year of Manufacture', 'value': '2022'},
            {'key': 'SIM Type', 'value': 'Dual Sim'}
        ]},
        {'key': 'OS & Processor Features', 'values': [
            {'key': 'Operating System', 'value': 'Andriod'
            },
            {'key': 'Processor Type', 'value': 'MediaTek'
            },
            {'key': 'Processor Core', 'value': 'Octa Core'
            },
            {'key': 'PCS', 'value': '2 GHz'
            },
        ]
    }
        
    ]
}

into something like this

General
Model Number: REDMI
Year of Manufacture: 2022
SIM Type: Dual Sim
OS & Processor Features
Operating System: Andriod
Processor Type: MediaTek
Processor Core: Octa Core
PCS', 'value': '2 GHz\

Here you go:

let a = {...}
let formattedText = ""
for (let spec of a["spec"]) {
  formattedText += spec["key"] + "\n"
  for (let value of spec["values"]) {
    formattedText += `\t${value["key"]} : ${value["value"]}\n`
  }
}

return formattedText

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