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

时间:2019-03-08 09:06:24

标签: javascript json angular

我有一个JSON输入,可以输入任意多个级别。 我想在所有级别中添加一个属性

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

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

2 个答案:

答案 0 :(得分:2)

如果您要向每个项目及其每个子项添加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)

答案 1 :(得分:0)

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

// https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
nTypeof = function (obj) {
  return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[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)

相关问题