簡體   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