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:[{}] }

阅读量:18

点赞量:0

问AI
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: {}, } )