javascript - 遍历嵌套的 JSON 对象并添加属性

标签 javascript json angular

我有一个可以进入任意数量级别的 JSON 输入。 我想在所有级别添加一个属性

[{
  title:' ' ,
  id : ' ',
  description: ' ',
  date :' ',
  children:[{
     children : [{ 
     ....
      }]
    title:' ' ,
    id : ' ',
    description: ' ',
    date :' ',  
   }]
  },
  title:' ' ,
  id : ' ',
  description: ' ',
  date :' ',
  children:[{
    children : [{ 
     ....
    }]
   ...
    }]
  }]

我想在每个级别添加一个 isShow 属性。 我如何进入 JSON 的内部层次?

最佳答案

如果您想递归地向每个项目及其每个子项添加一个 isShown 属性,这里有一种方法可以做到这一点。

此解决方案使用 Array.isArray(x)检查 x 是否为数组并且 x instanceof Object检查 x 是否是一个对象。如果 x 是一个数组 forEach()用于将函数应用于每个条目,如果 x 是一个对象,则添加属性并使用 forEach 将函数应用于每个子项。

const data = [{
  title: '',
  id: '',
  description: '',
  date: '',
  children: [{
    children: [{}],
    title: '',
    id: '',
    description: '',
    date: '',  
  }]
}, {
  title: '',
  id: '',
  description: '',
  date: '',
  children: [{ children: [{}] }]
}];

function addIsShown(x) {
  if (Array.isArray(x)) { // if data is an array
    x.forEach(addIsShown); // call the function on each item
  } else if (x instanceof Object) { // otherwise, if data is an object
    x.isShown = true; // add prop to object
    (x.children || []).forEach(addIsShown); // and call function on each child
  }
}

addIsShown(data);

console.log(data)

关于javascript - 遍历嵌套的 JSON 对象并添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55059856/

相关文章:

javascript - 在 Angular 2 的扩展 RouterOutlet 中导入自定义服务以进行身份​​验证

c# - 在反序列化之前为 XSS 清除 JSON

json - Angular 2 应用程序部署到 Azure 时出现错误 404

javascript - YouTube 订阅按钮未显示

javascript - FineUploader allowedExtensions 使用数组?

python - 在 python 字典中替换 None

javascript - 如何将 JSON 字符串转换为 javascript 对象?

javascript - Angular 如何测试需要位置的组件

javascript - 根据行的值将行拼接到索引处的 Javascript 对象中

javascript - JQuery 确定是否所有复选框列表(在 div 中)都已被选中