我得到了一个对象数组
const users= [{
Location: {
label: "aa",
value: "aa"
},
Name: "test7"
id: "002"
},
Location: {
label: "aa",
value: "aa"
},
Name: "test4"
id: "003"
},
{
Location: {
label: "ss",
value: "ss"
},
Name: "test4"
id: "004"
}]
我想首先使用 Location.lable 然后使用名称(升序)对数组进行排序
这是我已经完成的操作,但它不起作用
const dynamicSort = property => {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function(a, b) {
var result;
if (property === "deviceLocation")
result =
a[property].label < b[property].label
? -1
: a[property].label > b[property].label
? 1
: 0;
else
result =
a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0;
return result * sortOrder;
};
};
users.sort(dynamicSort("deviceLocation"))
结果应该是这样的:
const users= [{
Location: {
label: "aa",
value: "aa"
},
Name: "test4"
id: "003"
},
Location: {
label: "aa",
value: "aa"
},
Name: "test7"
id: "002"
},
{
Location: {
label: "ss",
value: "ss"
},
Name: "test4"
id: "004"
}]
如何首先使用 Location.label 然后使用 Name 对数组对象进行排序。我尝试了 lodash _.groupBy 排序后但没有成功
最佳答案
首先,您应该在问题中使用 JSON 或 JavaScript 对象。
然后,您可以创建一个排序函数,首先对用户位置的标签进行排序,然后对用户的名称进行排序。
console.log(getUsers().sort(userComparator));
function userComparator(userA, userB) {
let diff = userA.Location.label.localeCompare(userB.Location.label);
return diff === 0 ? userA.Name.localeCompare(userB.Name) : diff;
}
function getUsers() {
return [{
"Location": {
"label": "colombo",
"value": "colombo"
},
"Name": "test7",
"id": "002"
}, {
"Location": {
"label": "jaffna",
"value": "jaffna"
},
"Name": "test4",
"id": "004"
}, {
"Location": {
"label": "colombo",
"value": "colombo"
},
"Name": "test4",
"id": "003"
}];
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
关于javascript - 如何对对象数组进行分组和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60455989/