I'm writing a code where I'm building a JSON from another JSON using some conditions. Here is my code.
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));
when I run this. src is displayed as a separate object., but I want it to be inside the existing object. Here is what I get as my current output.
{
"richContent": [
[
{
"type": "info",
"title": "test desc"
},
{
"src": {
"rawUrl": "https://example.com/images/logo.png"
}
}
]
]
}
How can I change it to look like
{"richContent": [
[
{
"type": "info",
"title": "test desc",
"image": {
"src": {
"rawUrl": "https://example.com/images/logo.png"
}
}
}
]
]
}
Instead of using the Object.keys code you could try the following approach.
richResult.richContent[0][0].img = img;
Complete code is as follows
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));