gpt4 book ai didi

javascript - 将 2 个 api 响应的结果合并到一个 JavaScript 数组中

转载 作者:行者123 更新时间:2023-12-02 22:55:21 25 4
gpt4 key购买 nike

我有两个不同的 api 响应想要合并。第一个 api 响应如下所示

"Data1":[ 
{
"name": "First Officer",
"status": "ACTIVE",
"id": "111"
},
{
"name": "Second Officer",
"status": "DELETED",
"id": "222"
},
{
"name": "Third Officer",
"status": "ACTIVE",
"id": "333"
}
],
Data2[],
Data3[]

第二个响应是获取官员的最新位置,如下所示

 [
{
"id": "111",
"latest_position": "Elm Street"
},
{
"id": "333",
"latest_position": "Newton Sr. Street"
}
]

我需要将上面 API 的两个响应合并为一个像这样的数组

["111","First Officer","Elm Street"]
["333", "Third Officer","Newton Sr. Street"]

但是我得到的是这样的数据

 ["333","Third Officer","Elm Street"]
["333", "Third Officer","Newton Sr. Street"]

你知道我下面的代码错误在哪里吗

$.ajax({
url: api_url+'search?keyword='+keyword,
type: 'GET',
success: function(response) {
//console.log(response);
var keys = Object.keys(response.data);
for (var i = 0; i < keys.length; i++) {
var data = response.data[keys[i]]
for (var j = 0; j < data.length; j++) {
var name = data[j].name;
var sid = data[j].id;
$.ajax({
url: api_url+'positions?filter=%7B%22where%22%3A%7B%22user_id'+sid,
type: 'GET',
success: function(response2) {
//console.log(response);
for (var i = 0; i < response2.length; i++) {
var loc = response2[i].latest_position;
var obj = {
'id' : sid,
'name' : name,
'loc' : loc,

};

arrObj.push(obj);

}
}
})
}
}


console.log(arrObj);

谢谢

最佳答案

您可以使用Array.find通过 id 从第二个响应中搜索项目。

类似这样的事情:

const response1 = [{
"name": "First Officer",
"status": "ACTIVE",
"id": "111"
},
{
"name": "Second Officer",
"status": "DELETED",
"id": "222"
},
{
"name": "Third Officer",
"status": "ACTIVE",
"id": "333"
}
];

const response2 = [{
"id": "111",
"latest_position": "Elm Street"
},
{
"id": "333",
"latest_position": "Newton Sr. Street"
}
];

const merged = response2.map(item => {
const resp1Item = response1.find(r => r.id === item.id);

return { ...item,
...resp1Item
}
});

console.log(merged);

关于javascript - 将 2 个 api 响应的结果合并到一个 JavaScript 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58005345/

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