2 回答
TA贡献1802条经验 获得超4个赞
使用此代码更新您的数据对象
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
})
TA贡献1836条经验 获得超3个赞
您可以将sortmethod 与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);
添加回答
举报