You can use recursion for this, by repeating the addDefault()
function for each nested array.(您可以为此使用递归,方法是为每个嵌套数组重复addDefault()
函数。)
By looping over each object in the array, you can check whether or not it has content
, if it doesn't, you can add your "Default Content (0)" string to it:(通过遍历数组中的每个对象,可以检查它是否具有content
,如果没有,则可以向其中添加“默认内容(0)”字符串:)
const data = [{title:"Admin Services",content:"admin",links:[{title:"Report",content:"",links:[{title:"Notifications",content:"Notify",links:[{title:"Send",content:"",links:[{title:"read",content:"",links:[]}]}]}]},{title:"Script",content:"script",links:[{title:"Execute",content:"",links:[]}]},{title:"Process",content:"",links:[]}]}]; const addDefault = (arr, level=0) => { arr.forEach(obj => { obj.content = obj.content || `Default Content (${level++})`; addDefault(obj.links, level); level = 0; }); } addDefault(data); console.log(data);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…