Estoy escribiendo un código en el que construyo un JSON a partir de otro JSON usando algunas condiciones. Aquí está mi código.
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)); cuando ejecuto esto. src se muestra como un objeto separado, pero quiero que esté dentro del objeto existente. Esto es lo que obtengo como mi salida actual.
{ "richContent": [ [ { "type": "info", "title": "test desc" }, { "src": { "rawUrl": "https://example.com/images/logo.png" } } ] ] }¿Cómo puedo cambiarlo para que se vea como
{"richContent": [ [ { "type": "info", "title": "test desc", "image": { "src": { "rawUrl": "https://example.com/images/logo.png" } } } ] ] }En lugar de usar el código Object.keys, puede probar el siguiente enfoque.
richResult.richContent[0][0].img = img;
El código completo es el siguiente
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));