繁体   English   中英

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

[英]Traverse thorough Nested JSON Object and add attribute

我有一个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) 

这听起来像是用于恢复功能的工作...

 // https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/ nTypeof = function (obj) { return ({}).toString.call(obj).match(/\\s([az|AZ]+)/)[1].toLowerCase(); }; var input = `[{ "title":" " , "id" : " ", "description": " ", "date" :" ", "children":[{ "title":" " , "id" : " ", "description": " ", "date" :" " }] }]` var output = JSON.parse(input, // reviver function called for each node in the JSON (key,value)=>{ if(nTypeof(value) === "object") value.isShown = 0 return value }) console.log(output) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM