[英]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.