Jason Cooper Jason Cooper - 4 months ago 16
Javascript Question

How to join/merge two json objects using sailsjs-nodejs

Hello I am new to Sailsjs-Nodejs. In my controller I have two JSON Objects I need to merge/join so I can make third to send response

res.send(obj1) output

[
{
total_fare: "376",
arrival_to: "ABV"
},
{
total_fare: "312",
arrival_to: "ACC"
},
{
total_fare: "432",
arrival_to: "BFN"
}
]


res.send(obj2) output

[
{
url: "nigeria.php",
country: "Nigeria",
city_code: "ABV"
},
{
url: "ghana.php",
country: "Ghana",
city_code: "ACC"
},
{
url: "south-africa.php",
country: "South Africa",
city_code: "BFN"
}
]


Here is my expected result
res.send(obj3) should output

[
{
url: "nigeria.php",
country: "Nigeria",
city_code: "ABV",
total_fare: "376",
arrival_to: "ABV"
},
{
url: "ghana.php",
country: "Ghana",
city_code: "ACC",
total_fare: "312",
arrival_to: "ACC"
},
{
url: "south-africa.php",
country: "South Africa",
city_code: "BFN",
total_fare: "432",
arrival_to: "BFN"
}
]

Answer

You can probably do as follows without modifying the source arrays;

var arr = [{total_fare: "376",arrival_to: "ABV"},
           {total_fare: "312",arrival_to: "ACC"},
           {total_fare: "432",arrival_to: "BFN"}],
    brr = [{url: "nigeria.php",country: "Nigeria",city_code: "ABV"},
           {url: "ghana.php",country: "Ghana",city_code: "ACC"},
           {url: "south-africa.php",country: "South Africa",city_code: "BFN"}],
 merged = arr.map((o,i) => Object.assign({},o,brr[i]));
 console.log(merged);