简体   繁体   中英

Traverse thorough Nested JSON Object and add attribute

I have a JSON input which can go to any number of levels. I want to add the one attribute in all levels

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

I want to add an isShow attribute at each level. How do I get into the inner levels for JSON?

If you want to add an isShown property to each item and to each of its children recursively, here is a way to do it.

This solution uses Array.isArray(x) to check if x is an array and x instanceof Object to check if x is an object. If x is an array forEach() is used to apply the function to each entry, if x is an object, the property is added and forEach is used to apply the function to each child.

 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) 

This sounds like a job for a reviver function...

 // 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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