从REST API返回数组中的前2个json名称/值对



场景:我有两个REST端点,

https://myrestapi/user/names和https://myrestapi/user/age

/names端点包含一个JSON数组,如下所示:

{
"0x0": "John",
"0x1": "Cassy",
"0x2": "Christopher",
"0x3": "Jarred",
"0x4": "Simon",
"0x5": "Eddy",
"0x6": "Lara",
"0x7": "Marcel",
"0x8": "Simone"
}

/age端点包含一个JSON数组,如下所示:

{
"0x0": "36",
"0x1": "24",
"0x2": "21",
"0x3": "29",
"0x4": "24",
"0x5": "38",
"0x6": "45",
"0x7": "37",
"0x8": "26"
}

运行以下代码,我可以显示阵列中的所有数据:

$.when( 
$.getJSON( "https://myrestapi/user/names" ), 
$.getJSON( "https://myrestapi/user/age" )
).done(( a1, a2 ) => {
// a1[0] gets list of name
// a2[0] gets list of ages
console.log(a1[0])
console.log(a2[0])
})

如果我只想要前两对的名字和年龄呢?

示例:[{"user_id":"0x0","name":"John","age":36},{"用户id":"0x1","姓名":"凯西","年龄":24}]

有人能提供一些方向吗?

试试这个,你可以定义你想在for循环中列出的用户数量,例如i<3将产生3个名称/值对

let names = {
"0x0": "John",
"0x1": "Cassy",
"0x2": "Christopher",
"0x3": "Jarred",
"0x4": "Simon",
"0x5": "Eddy",
"0x6": "Lara",
"0x7": "Marcel",
"0x8": "Simone"
}

let ages = {
"0x0": "36",
"0x1": "24",
"0x2": "21",
"0x3": "29",
"0x4": "24",
"0x5": "38",
"0x6": "45",
"0x7": "37",
"0x8": "26"
}
let result = [];
for(let i = 0; i < 3; i++){
result.push({'user_id': Object.keys(names)[i], 'name': Object.values(names)[i], 'age': Object.values(ages)[i]})
}
console.log(result)

API返回JSON对象,而不是JSON数组。因此,不存在";第一个N〃;元素。如果您更改API代码以返回JSON数组,那么您可以获得;前2个元素";现在,你可以想到你想选择的ID列表:

const listOfIds = ['0x0', '0x1'];
const dataYouWant = listOfIds.map(id => ({
user_id: id,
name: a1[id],
age: a2[id],
}));

最新更新