You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 17:45:03