gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:09:56 25 4
gpt4 key购买 nike

我有一组像这样的对象:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com