我有一个可以进入任意数量级别的 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)
关于javascript - 遍历嵌套的 JSON 对象并添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55059856/