按属性数组对对象数组进行排序

4

我有一个对象数组,类似于这个:

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: [{}],
    }
];

我希望你能用JavaScript按属性4对其进行排序,因此如果对象具有属性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不存在,则返回“Undefined”。我该如何使用Array.Sort对其进行排序?
3个回答

3
您可以使用length属性和||运算符对数组进行排序。

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);


2

一种方法是解构然后使用默认数组,如果属性不存在。然后你可以通过数组长度的差异来 .sort()

const 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: [{}], } ];

const res = skillBuddys.sort(
  ({Property4: a = []}, {Property4: b = []}) => b.length - a.length
);

console.log(res);


1
SkillBuddys
.filter((x) => Array.isArray(x.Property4)  )
.sort( (a,b) => b.Property4.length - a.Property4.length)
.concat( SkillBuddys.filter((x) => !Array.isArray(x.Property4))

这将给你一个数组,其中包含按内部数组长度排序的 Property4 元素,并在其余元素之后以未指定的顺序排列(你可以使用自己选择的排序方式进行排序)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接