JavaScript查找嵌套对象中component为get-all的项并新增属性的实现方法
问题说明
你当前编写的递归函数仅能匹配到第一个component属性为"get-all"的对象,找到后会直接终止递归,无法处理嵌套结构中所有符合条件的对象,同时无异步依赖的情况下使用async/await属于不必要的开销。
修正后代码
function addStoriesToAllGetAllComponents(theObject) { // 遍历数组元素 if (theObject instanceof Array) { for (let i = 0; i < theObject.length; i++) { addStoriesToAllGetAllComponents(theObject[i]); } return } // 处理对象 if (theObject instanceof Object) { // 匹配到目标对象则新增stories属性 if (theObject.component === 'get-all') { theObject.stories = ["some example stories"] } // 递归遍历所有嵌套的对象/数组属性 for (const prop in theObject) { const value = theObject[prop] if (value instanceof Object || value instanceof Array) { addStoriesToAllGetAllComponents(value) } } } }
使用方式
直接将你的原始嵌套对象作为参数传入函数即可,函数会直接修改原对象,所有符合条件的对象都会被新增stories属性,和你给出的预期输出效果一致。
内容的提问来源于stack exchange,提问作者jules-la
相关产品推荐
相关产品推荐

