遍历带有分层子级的json并添加键值对

时间:2019-06-12 15:50:30

标签: javascript arrays json object tree

我想将现有数据转换为其他数据。请在下面找到现有代码和预期代码。

现有:

{     “ title”:“ title1”,     “孩子”:[         {         “ title”:“标题”,         “儿童”:         [             {             “ title”:“ test”,             “儿童”:             [                            {                  “ title”:“ testchild”,

            },
           {
              "title": "Descriptionchild",
            }
             ]

            },
            {
                "title": "Description",
            }
        ]
    }
]

}

预期:

{     “ title”:“ title1”,     “ customId”:“ title1-xx”     “孩子”:[         {             “ title”:“标题”,             “ customId”:“ Header1-xx”,             “儿童”:             [                 {                     “ title”:“ test”,                     “ customId”:“ test1-xx”,                     “儿童”:                         [                             {                                 “ title”:“ testchild”,                                 “ customId”:“ testchild1-xx”

                        },
                        {
                            "title": "Descriptionchild",
                            "customId": "Descriptionchild1-xx"
                        }
                    ]

            },
            {
                "title": "Description",
                "customId": "Description1-xx"
            }
        ]
    }
]

}

1 个答案:

答案 0 :(得分:0)

我们可以定义一个接受数组并递归添加此属性的函数:

// input must be array
function recursivelyAddCustomId(input) {
  // if input is not empty i.e. child is not empty
  if (input != null) {
    // for each child object in array
    for (let obj of input) {
      // set custom id
      if (obj.title != null) {
        obj.customId = obj.title + '-xx';
      }
      // recurse (doesn't matter if child exists)
      recursivelyAddCustomId(obj.child);
    }
  }
}
// put input as array
recursivelyAddCustomId([input]);
console.log(input);

请注意,此函数的输入必须为数组,因此必须先将第一个对象转换为数组。

请让我知道是否需要澄清。

注意:在代码块中进行注释