gpt4 book ai didi

javascript - 如何使用 sailsjs-nodejs 连接/合并两个 json 对象

转载 作者:行者123 更新时间:2023-12-03 06:22:29 24 4
gpt4 key购买 nike

您好,我是 Sailsjs-Nodejs 的新手。在我的 Controller 中,我有两个需要合并/连接的 JSON 对象,这样我就可以创建第三个对象来发送响应

res.send(obj1) 输出

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

res.send(obj2)输出

[
{
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"
}
]

这是我的预期结果res.send(obj3) 应该输出

[
{
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"
}
]

最佳答案

您可以执行以下操作,而无需修改源数组;

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);

关于javascript - 如何使用 sailsjs-nodejs 连接/合并两个 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38804963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com