我有一个简单的JavaScript嵌套对象,如下所示。我不知道会有多少孩子,但这就是我所收到的数据的本质。我怎样才能转化成预期的结果?
原始数据嵌套json
{
"work": {
"children": {
"abc": {
"label": "Work address",
"name": "address"
},
"xyz": {
"label": "Work phone",
"name": "phone"
},
"efg": {
"children": {
"position": {
"label": "Work",
"name": "position"
},
"employees": {
"label": "Number of employees",
"name": "employees"
}
}
}
}
}
}期望
{
work: {
"address": "",
"phone": "",
"details": {
"position": "",
"employees": ""
}
}
}我尝试的是下面的代码
var jsonschema = root.json
var newjson = {}
for (let name in jsonschema) {
if (jsonschema.children.length > 0 ) {
//add a empty object to newjson
}
}发布于 2020-08-27 05:40:16
您可以使用通用的map函数和递归的transform函数-
const map = (f, t) =>
Object.fromEntries(Object.entries(t).map(([ k, v ]) => [ k, f(v) ]))
const transform = (t = {}) =>
t.name
? ""
: map(transform, t.children || t)
const input =
{"work":{"children":{"address":{"component":"BaseInput","label":"Work address","name":"address"},"phone":{"component":"BaseInput","label":"Work phone","name":"phone"},"details":{"children":{"position":{"component":"BaseInput","label":"Work position","name":"position"},"employees":{"component":"BaseInput","label":"Number of employees","name":"employees"}}}}}}
console.log(transform(input))
https://stackoverflow.com/questions/63609688
复制相似问题