如何更改嵌套对象数组内的所有键名称javascript

muh*_*zia -1 javascript arrays object

我嵌套了如下所示的对象数组:

const data = [
  {text: 'node 1'}, 
  {text: 'node 2', chapter_playlist: [{text: 'node 2-1', lesson_playlist: [{text: 'node 3-1'}]}]},
  {text: 'node 3'}, 
  {text: 'node 4', chapter_playlist: [{ text: 'node 4-1' }]}
]
Run Code Online (Sandbox Code Playgroud)

如何将每个嵌套属性(如chapter_playlistlesson_playlist)重命名为“ children ”?

基本上我想更改具有更多子项的属性的名称,如果没有子项则无需更改它。我仍然很困惑如何改变它

预期成绩

const data = [
  {text: 'node 1'}, 
  {text: 'node 2', children: [{text: 'node 2-1', children: [{text: 'node 3-1'}]}]},
  {text: 'node 3'}, 
  {text: 'node 4', children: [{ text: 'node 4-1' }]}
]
Run Code Online (Sandbox Code Playgroud)

Mik*_*ans 9

有趣的事实:如果您出于某种原因需要遍历一个对象,JSON.stringify()是您的朋友。

不是因为您想将数据转换为 JSON 字符串,而是因为它也是一个对象迭代器,可让您使用替换函数在每个级别执行任意处理:

const data = [
  {text: 'node 1'}, 
  {text: 'node 2', chapter_playlist: [{text: 'node 2-1', lesson_playlist: [{text: 'node 3-1'}]}]},
  {text: 'node 3'}, 
  {text: 'node 4', chapter_playlist: [{ text: 'node 4-1' }]}
]

const rewriteList = [`chapter_playlist`, `lesson_playlist`];

function replacer(key, value) {
  // If the value at this depth is an object (but not an iterable
  // like array or Set or Map), then rebind the properties you
  // need rebound, provided they exist:
  if (typeof value === `object` && !value[Symbol.iterator]) {
    rewriteList.forEach(prop => {
      if (value[prop]) {
        // By editing "value", we're directly updating "data".
        value.children = value[prop];
        delete value[prop];
      }
    });
  }
  return value;
}

JSON.stringify(data, replacer);

console.log(data)
Run Code Online (Sandbox Code Playgroud)