gpt4 book ai didi

javascript,lodash :- how to sort array of objects where object having object inside

转载 作者:太空宇宙 更新时间:2023-11-04 15:41:05 25 4
gpt4 key购买 nike

var a = [
{
"subObj1": {
"key1":10722905,
"key2":"0080817626"
},
"outerKey1":"abcd",
"outerKey2":"defg"
},
{
"subObj1": {
"key1":123456,
"key2":"0987654"
},
"outerKey1":"pqrs",
"outerKey2":"ased"
}
]

我需要分别使用key1和outerkey1对这个对象数组进行排序。该逻辑已经实现。

_.sortBy(a,'outerKey1') -> 这工作正常。

_.sortBy(a,'key1') -> 这不起作用。

_.sortBy(a,'subObj1.key1') -> 这也不起作用。

有没有办法使用 lodash _.sortBy 函数使用对象的内部键(如 key1 或 key2)对这个对象数组进行排序?

最佳答案

仅使用 JavaScript,您可以将 Array.prototype.sort() 与自定义回调函数一起使用:

var sorted = arr.sort(function(a, b) {
a.subObj1.key1 - b.subObj1.key1
});

演示:

var arr = [{
"subObj1": {
"key1": 10722905,
"key2": "0080817626"
},
"outerKey1": "abcd",
"outerKey2": "defg"
},
{
"subObj1": {
"key1": 123456,
"key2": "0987654"
},
"outerKey1": "pqrs",
"outerKey2": "ased"
}
];

var sorted = arr.sort(function(a, b) {
a.subObj1.key1 - b.subObj1.key1
});

console.log(sorted);

编辑:

如果您想使用 lowdash 来完成此操作,则可以将 _.sortBy() 与自定义排序器函数一起使用:

var customSorter = function(obj) {
return obj.subObj1.key1;
};
var sorted = _.sortBy(arr, customSorter);

演示:

var arr = [{
"subObj1": {
"key1": 10722905,
"key2": "0080817626"
},
"outerKey1": "abcd",
"outerKey2": "defg"
},
{
"subObj1": {
"key1": 123456,
"key2": "0987654"
},
"outerKey1": "pqrs",
"outerKey2": "ased"
}
];

var customSorter = function(obj) {
return obj.subObj1.key1;
};
var sorted = _.sortBy(arr, customSorter);

console.log(sorted);
<script src="http://underscorejs.org/underscore-min.js"></script>

关于javascript,lodash :- how to sort array of objects where object having object inside,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43865532/

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