我有一個看起來像這樣的物件陣列:
[
{
"text":"Same but with checkboxes",
"opened": true,
"children":[
{
"text":"initially selected",
"opened":true
},
]
},
{
"text":"Same but with checkboxes",
"opened":true,
"children":[
{
"text":"initially open",
"opened":true,
"children":[
{
"text":"Another node",
"opened":true,
}
]
},
{
"text":"custom icon",
"opened":true,
},
{
"text":"disabled node",
"opened":true,
}
]
},
{
"text":"And wholerow selection",
"opened":true,
}
]
我想知道是否可以將打開的鍵的值(例如)更改為所有級別的所有物件.. 我該怎么做?
我嘗試過類似的事情但沒有成功
myArray.map(e => ({ ...e, opened: false }))
uj5u.com熱心網友回復:
創建一個遞回函式 - 如果被迭代的物件有一個children陣列,則為所有這些子物件呼叫它。
const input=[{text:"Same but with checkboxes",opened:!0,children:[{text:"initially selected",opened:!0}]},{text:"Same but with checkboxes",opened:!0,children:[{text:"initially open",opened:!0,children:[{text:"Another node",opened:!0}]},{text:"custom icon",opened:!0},{text:"disabled node",opened:!0}]},{text:"And wholerow selection",opened:!0}];
const closeAll = (obj) => {
obj.opened = false;
obj.children?.forEach(closeAll);
};
input.forEach(closeAll);
console.log(input);
uj5u.com熱心網友回復:
遞回可以提供幫助。遞回搜索所有物件的openedkey 并將其切換為 false。
var data = [ { "text": "Same but with checkboxes", "opened": true, "children": [ { "text": "initially selected", "opened": true }, ] }, { "text": "Same but with checkboxes", "opened": true, "children": [ { "text": "initially open", "opened": true, "children": [ { "text": "Another node", "opened": true, } ] }, { "text": "custom icon", "opened": true, }, { "text": "disabled node", "opened": true, } ] }, { "text": "And wholerow selection", "opened": true, } ];
function run(data) {
for (let subData of data) {
if (subData["opened"])
subData["opened"] = false;
if (subData["children"])
run(subData["children"])
}
}
run(data)
console.log(data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/382255.html
標籤:javascript 数组 json 目的 ecmascript-6
