我正在编写一个代码,我正在使用某些条件从另一个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"
}
}
}
]
]
}
不使用对象。键代码,您可以尝试以下方法。
richResult.richContent[0][0]。
完整代码如下
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));