js递归如何生成该数据的预览json格式?
需求就是通过json生成json,简化后的格式如下,如何通过递归的方式生成这些数据表示的最终格式?求教
//这个是各个类型生成的默认值
const defaultVal = {
string:"默认值",
int:1,
float:0.1,
double:10.34,
boolean:false,
array:null
}
//这个是json待转化的
[
{
"type": "object",
"propertyName": "user",
"children": [
{
"type": "string",
"propertyName": "name",
"children": null
},
{
"type": "int",
"propertyName": "age",
"children": null,
},
{
"type": "array",
"propertyName": "data",
"children": [
{
"type": "object",
"name": "name",
"children": null
}
]
}
]
}
]
//上述转化结果为:
{
name:'默认值',
age:1,
data:[{}]
}
回复
1个回答

test
2024-06-24
function toData(rule, defVal, init) {
const copy = val => JSON.parse(JSON.stringify(val));
const initial = init ?? copy(defVal[rule.type]);
return rule.children ? rule.children.reduce((res, v) => {
if(Array.isArray(res)) res.push(toData(v, defVal));
else if({}.toString.call(res) == '[object Object]') toData(v, defVal, res[v.propertyName] = copy(defVal[v.type]))
return res;
}, initial) : initial;
}
toData(
{
"type": "object",
"propertyName": "user",
"children": [
{
"type": "string",
"propertyName": "name",
"children": null
},
{
"type": "int",
"propertyName": "age",
"children": null,
},
{
"type": "array",
"propertyName": "data",
"children": [
{
"type": "object",
"name": "name",
"children": null
}
]
}
]
},
{
string:"默认值",
int:1,
float:0.1,
double:10.34,
boolean:false,
array:[],
object: {},
}
)
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容