gpt4 book ai didi

javascript - lodash 的对象顺序

转载 作者:行者123 更新时间:2023-12-01 02:55:51 25 4
gpt4 key购买 nike

我想按 PERIOD 属性对此对象进行排序。

由于对象和数组在一起,我很困惑,有人有什么想法吗?

我的代码

const obj = 
{
"1": [
{
"attributes": {
"Period": 2000,
"name": "AP 1"
}
},
{
"attributes": {
"Period": 1991,
"name": "AP 2"
}
}
],
"2": [
{
"attributes": {
"Period": 1991,
"name": "AP 3"
}
},
{
"attributes": {
"Period": 2000,
"name": "AP 4"
}
}
]
}

_.orderBy(obj, ['Period'], ['asc']);

console.log(obj)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>

返回结构必须与输入结构相同。您不需要丢失属性名称,只需丢失句点

我的预期代码

{
"1": [
{
"attributes": {
"Period": 1991,
"name": "AP 2"
}
},
{
"attributes": {
"Period": 2000,
"name": "AP 1"
}
}
],
"2": [
{
"attributes": {
"Period": 2000,
"name": "AP 4"
}
},
{
"attributes": {
"Period": 1991,
"name": "AP 3"
}
}
]
}

我使用的lodash版本:4.17.4

最佳答案

我认为这就是您正在寻找的:

var obj = 
{
"1": [
{
"attributes": {
"Period": 2000,
"name": "AP 1"
}
},
{
"attributes": {
"Period": 1991,
"name": "AP 2"
}
}
],
"2": [
{
"attributes": {
"Period": 2000,
"name": "AP 3"
}
},
{
"attributes": {
"Period": 1991,
"name": "AP 4"
}
}
]
}

obj = _.mapValues(obj, function(inner){
return _.orderBy(inner, ['attributes.Period'], ['dsc']);
});

console.log(obj)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>

关于javascript - lodash 的对象顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46720299/

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