我正在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]
}]
现在如何
products
的数量对用户进行排序product
键将产品ID转换为对象products
排序id
键期望
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
进行排序。
答案 0 :(得分:3)
使用此代码更新数据对象
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
})
答案 1 :(得分:0)
您可以将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);