javascript - 使用附加 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"
}
}
}
]
]
}
解决方案
您可以尝试以下方法,而不是使用 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));
推荐阅读
- vue.js - 防止移动到下一个选项卡 vue.js 向导
- linux - Linux:从 find 命令快速创建格式化输出文件 (csv)
- ubuntu - VS Code 连接到 WSL Ubuntu 20.04 LTS,失败并出现错误:无法获取远程环境
- git - Pycharm 终端指向错误的 git 可执行文件(MacOS)
- python - 我需要将列列表中的每个元素转换为 python pandas 中的新列
- android - 连接到服务器时更改活动 (TCP)
- node.js - 在 windows 上安装 vue/cli 时出错
- r - 动态小标题的迭代问题
- javascript - 如何从预定义的对象呈现 Ant Design 图标
- javascript - 通过 Iframe postMessage 传递回调?