我有一组像这样的对象:
var SkillBuddys = [
{
Property1: "1",
Property2: "Test",
Property3: "Data",
Property4: [{},{},{}],
}, {
Property1: "2",
Property2: "Test2",
Property3: "Data2"
}, {
Property1: "3",
Property2: "Test3",
Property3: "Data3",
Property4: [{},{}],
}, {
Property1: "4",
Property2: "Test4",
Property3: "Data4"
}, {
Property1: "5",
Property2: "Test5",
Property3: "Data5",
Property4: [{}],
}
];
我想在属性 4 上使用 javaScript 对其进行排序,所以如果对象具有属性 4 并包含一个数组。像这样:
var SkillBuddys = [
{
Property1: "1",
Property2: "Test",
Property3: "Data",
Property4: [{},{},{}],
}, {
Property1: "3",
Property2: "Test3",
Property3: "Data3",
Property4: [{},{}],
}, {
Property1: "5",
Property2: "Test5",
Property3: "Data5",
Property4: [{}],
}, {
Property1: "2",
Property2: "Test2",
Property3: "Data2"
}, {
Property1: "4",
Property2: "Test4",
Property3: "Data4"
}
];
如果属性 4 不存在,则返回“未定义”。如何使用 Array.Sort 对其进行排序?
最佳答案
你可以 sort
数组使用 length
属性(property)和||
运算符(operator)。
var array = [ { Property1: "1", Property2: "Test", Property3: "Data", Property4: [{},{},{}], }, { Property1: "2", Property2: "Test2", Property3: "Data2" }, { Property1: "3", Property2: "Test3", Property3: "Data3", Property4: [{},{}], }, { Property1: "4", Property2: "Test4", Property3: "Data4" }, { Property1: "5", Property2: "Test5", Property3: "Data5", Property4: [{}], } ];
array.sort((a, b) => (b['Property4'] || []).length - (a['Property4'] || []).length);
console.log(array);
关于javascript - 按属性数组对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59375271/