如何在JS中格式化API JSON对数组对象的响应



我正在ReactJS中创建一个仪表板,并使用axios进行API调用。

API响应

const response = {
users: {
144: [
{
name: "Olivia",
},
{
mode: "c7",
fkProductsIds: [ 3, 2 ]
}
],
168: [
{
name: "Jill",
},
{
mode: "p9",
fkProductsIds: [ 1, 4, 5, 3 ]
}
],
202: [
{
name: "David",
},
{
mode: "p9",
fkProductsIds: [ 5, 1, 2 ]
}
]
},
products: [
{ 1: "PSM" },
{ 2: "FP" },
{ 3: "F2" },
{ 4: "Mark4" },
{ 5: "Astrid" },
]
}

我想把这个响应转换成一个数组,这样我就可以很容易地使用这个数据在UI上的列表中显示。

我已经尝试过的是

render(){
// --> Logic start
var data = Object.keys(response.users).map( userId => {
var tmp = {}
tmp.id       = userId
tmp.name     = response.users[userId][0].name
tmp.mode     = response.users[userId][1].mode
tmp.products = response.users[userId][1].fkProductsIds
return tmp
})
// <-- Logic end
return(
<ul> { data.map(user=><UserRow user={user} />) } </ul>
)
}

输出

data = [{
"id": "144",
"name": "Olivia",
"mode": "c7",
"products": [3, 2]
}, {
"id": "168",
"name": "Jill",
"mode": "p9",
"products": [1, 4, 5, 3]
}, {
"id": "202",
"name": "David",
"mode": "p9",
"products": [5, 1, 2]
}]

现在如何

  1. products的数量对用户进行排序
  2. product密钥中的产品ID转换为对象
  3. idproducts密钥进行排序

预期

const data = [
{
id  : 168,
name: "Jill",
mode: "p9",
products: [
{ id: 1, name: "PSM"    },
{ id: 3, name: "F2"     },
{ id: 4, name: "Mark"   },
{ id: 5, name: "Astrid" }
]
},
{
id  : 202,
name: "David",
mode: "p9",
products: [
{ id: 1, name: "PSM"    },
{ id: 2, name: "FP"     },
{ id: 5, name: "Astrid" }
]
},
{
id  : 144,
name: "Olivia",
mode: "c7",
products: [
{ id: 2, name: "FP" },
{ id: 3, name: "F2" },
]
}
]

正如你所看到的,所有用户都是按照他们拥有的products的数量排序的,用户的products键内的对象也是按照id排序的。

使用以下代码更新数据对象

var data = Object.keys(response.users).map( userId => {
var tmp = {}
tmp.id       = userId
tmp.name     = response.users[userId][0].name
tmp.mode     = response.users[userId][1].mode
tmp.products = response.users[userId][1].fkProductsIds.sort().map((pId) => {
let ret = {id: '', name: ''};
ret.id = pId;
let productById = response.products.filter((productIdx) => pId==Object.keys(productIdx)[0] );
if(productById && productById.length) {
ret.name = productById[0][pId];
}
return ret;
});
return tmp
})

您可以将sort方法与map结合使用。

const response = { users: { 144: [ { name: "Olivia", }, { mode: "c7", fkProductsIds: [ 3, 2 ] } ], 168: [ { name: "Jill", }, { mode: "p9", fkProductsIds: [ 1, 4, 5, 3 ] } ], 202: [ { name: "David", }, { mode: "p9", fkProductsIds: [ 5, 1, 2 ] } ] }, products: [ { 1: "PSM" }, { 2: "FP" }, { 3: "F2" }, { 4: "Mark4" }, { 5: "Astrid" }, ] }
getProductById = (id) => {
var elem = response.products.find(elem => elem[id]);
return {id : id, name: elem[id]}
}
var data = Object.keys(response.users)
.map( userId => 
({
id: userId, 
name: response.users[userId][0].name, 
mode: response.users[userId][1].mode, 
products: response.users[userId][1].fkProductsIds.sort().map(getProductById)
})).sort((a, b) => b.products.length - a.products.length)
console.log(data);

最新更新