CtrlAltDelete CtrlAltDelete - 1 year ago 128
Node.js Question

How to combine JSON data from multiple API's using NodeJS server

I have a NodeJS server that takes data from three different API's, and then sends the JSON from the three API's to my front end. Since I labeled the data from the three API's differently, it gets sent in three different arrays??(wrong term here maybe?). I'm trying to send it all in one array if possible!


var express = require('express');
var router = express.Router();
var request = require('request');
var app = express();

router.get("/", function(req, res){
var request = require('request-promise');
var data1;
var data2;
var data3;

data1 = JSON.parse(body);

return request("http://api2.com");
.then(function(body) {
data2 = JSON.parse(body);

return request("http://api3.com");
data3 = JSON.parse(body);

res.json("services.ejs", {data1: data1, data2: data2, data3: data3});

module.exports = router;


{"data1":[{All JSON from API #1}] - "Data2":[{All JSON from API #2}] - "Data3":[{All JSON from API #3}]}

Wanted Result:

{"allData": [{All JSON from API #1 #2 #3}]}

Answer Source

You can concatenate the 3 different results together into one array:

var alldata = data1.concat(data2).concat(data3);
res.json("services.ejs", {data: alldata});

Adjust accordingly, depending on exactly what you want in the results.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download