【发布时间】:2021-02-07 03:35:12
【问题描述】:
我想编写一个函数,它接受一个嵌套的 json 对象,并在每个表示对象本身的“路径”或层次结构的对象中写入一个 path 数组。 path 数组应该由父节点的id 填充。限制数组对象应该有一个路径,并且由于它们没有 id,因此根据该数组中的索引为它们提供一个枚举键。我的尝试低于但我在某些第 n 级没有得到正确的路径。
let nestedObject = {
"name":"bob",
"root_rule":{
"id":0,
"limits":[
{
"value":0
}
],
"rules":[
{
"id":15,
"limits":[
],
"rules":[
]
},
{
"id":16,
"limits":[
{
"value":25000000
},
{
"value":50001
},
{
"value":25000001
}
],
"rules":[
{
"id":20,
"limits":[
{
"value":0
}
],
"rules":[
{
"id":21,
"limits":[
],
"rules":[
]
}
]
}
]
}
]
}
}
function encodeNestedPath(nestedJson, pathList, type, parent = null) {
// process rood node
if ((typeof nestedJson) == 'object') {
if(nestedJson && nestedJson.condition && nestedJson.condition.name === 'ROOT') {
nestedJson['path'] = [String(nestedJson['id'])];
}
if(nestedJson.limits) {
encodeNestedPath(nestedJson.limits, nestedJson['path'], 'limits', nestedJson['id']);
}
if(nestedJson.rules) {
encodeNestedPath(nestedJson.rules, nestedJson['path'], 'rules', nestedJson['id']);
}
}
// traverse children nodes
if (Array.isArray(nestedJson)) {
for (const [i, element] of nestedJson.entries()) {
element['path'] = [];
if(String(parent)) {
element['path'].push(String(parent))
}
let parentId
if(!element.hasOwnProperty('id')) {
element['path'].push(type+'_'+i)
pathList = null
} else {
element['path'].push(String(element['id']))
parentId = element['id']
}
if(element.limits) {
encodeNestedPath(element.limits, element['path'], 'limits', parentId);
}
if(element.rules) {
encodeNestedPath(element.rules, element['path'], 'rules', parentId);
}
}
}
}
encodeNestedPath(nestedObject['root_rule'], null, null, null)
console.log(JSON.stringify(nestedObject['root_rule'], null, 4))
想要的输出是这样的。
【问题讨论】:
标签: javascript json recursion tree nested