Sunday 10 September 2017

Creating a JSON Object

What I'm trying to achieve: { "result": [ { "id": 1, "place_title": "Love ya", "image_path": "INSERT_IMAGE_PATH"; }, { "id": 2, "place_title": "Love ya" "image_path": "INSERT_IMAGE_PATH"; } ] } What I'm getting: { "result": [ { "id": 1, "place_title": "Love ya" }, { "id": 2, "place_title": "Love ya" } ] } Code:router.get("/listingImageAndTitle", function(req, res){ let sql = `SELECT * FROM airbnb.listings WHERE user_id = ?;` let values = [1] let listing_id_array = []; let listing_data_array = []; //get place_title and listing_id (for images table) in listing table app.con.query(sql, values, function(err, result){ for(let i = 0; i < result.length; i++){ listing_id_array.push(result[i].id); listing_data_array.push({ id:result[i].id, place_title: result[i].place_title }); } //get image_path in images table for(let i = 0; i < listing_id_array.length; i ++){ let sql = `SELECT * FROM airbnb.images WHERE listing_id = ?;` let values = [listing_id_array[i]]; app.con.query(sql, values, function(err, result){ console.log(result[0].image_path); //How do I get this part be part of the JSON Object? }); } res.json({ "result": listing_data_array }); }); });

Submitted September 11, 2017 at 03:31AM by badboyzpwns

No comments:

Post a Comment