首页 > 解决方案 > 使用附加 json 对象更新现有 json

问题描述

我正在编写一个代码,我正在使用某些条件从另一个 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));

当我运行这个。src显示为单独的对象。但我希望它位于现有对象内。这是我得到的当前输出。

{
  "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"
          }
        }
      }
    ]
  ]
} 

标签: javascriptjson

解决方案


您可以尝试以下方法,而不是使用 Object.keys 代码。

richResult.richContent[0][0].img = img;

完整代码如下

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
        }
    };

    richResult.richContent[0][0].img = img;   
}

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

推荐阅读