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

JavaScript 如何向已有JSON对象添加属性而非新增独立对象

问题描述

编写JavaScript代码时,需要基于源JSON按照条件生成新的JSON结构,现有代码如下:

var data = {
  "results": [{
    "rawData": {
      "description": "test desc",
      "name": "Plans",
      "c_activeInAnswers": true,
      "c_photo": {
        "url": "https://example.com/images/logo.png"
      }
    }
  }]
};

var answerJson = data.results[0].rawData;
var answerText = answerJson.description ?
  answerJson.description :
  answerJson.answer;


var richResult = {
  richContent: [
    [{
      type: "info",
      title: answerText,
    }, ],
  ],
};

if (answerJson.c_photo) {
  var img = {
    src: {
      rawUrl: answerJson.c_photo.url,
    },
  };
/* answerJson.push(img) */;
  Object.keys(richResult.richContent).map(
    function(object) {
      richResult.richContent[object].push(img);
    });
}

console.log(JSON.stringify(richResult));

运行代码后,当前输出中图片相关内容为独立对象,期望将图片作为image属性嵌入到已有的type为info的对象中。

当前输出

{
  "richContent": [
    [
      {
        "type": "info",
        "title": "test desc"
      },
      {
        "src": {
          "rawUrl": "https://example.com/images/logo.png"
        }
      }
    ]
  ]
} 

期望输出

{"richContent": [
    [
      {
        "type": "info",
        "title": "test desc",
        "image": {
          "src": {
            "rawUrl": "https://example.com/images/logo.png"
          }
        }
      }
    ]
  ]
} 
解决方案

原有代码的逻辑是把图片对象作为新元素插入到richContent的嵌套数组中,因此会变成独立对象。只需要修改answerJson.c_photo判断分支内的逻辑,直接给已有的info对象新增image属性即可。

最简修改(适配当前场景)

直接替换原有if分支的逻辑即可:

if (answerJson.c_photo) {
  var img = {
    src: {
      rawUrl: answerJson.c_photo.url,
    },
  };
  // 直接给已有的info对象赋值image属性
  richResult.richContent[0][0].image = img;
}

通用修改(适配多info对象场景)

如果richContent下可能存在多个type:info的对象,可以用遍历逻辑统一处理:

if (answerJson.c_photo) {
  var img = {
    src: {
      rawUrl: answerJson.c_photo.url,
    },
  };
  // 遍历所有嵌套内容,给所有type为info的对象添加image属性
  richResult.richContent.forEach(group => {
    group.forEach(item => {
      if (item.type === 'info') {
        item.image = img;
      }
    })
  })
}

内容的提问来源于stack exchange,提问作者Rakesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:57:02