gpt4 book ai didi

javascript - 在 JSON 对象中排序数组给出 TypeError : Cannot read property 'sort' of undefined

转载 作者:行者123 更新时间:2023-11-30 07:53:13 25 4
gpt4 key购买 nike

我想在 javascript 中对一个对象进行排序。我有这个 json:

var unsorted = {
"2014": [
{
"title": "Book",
"value": 10
},
{
"title": "Cheese",
"value": 2
}
],
"2015": [
{
"title": "Movie",
"value": 9
}
],
"2016": [
{
"title": "Slay",
"value": 90
},
{
"title": "Back",
"value": 22
}
],
"selected_year": 2015
};

所以我想把这些年里面的jsons按照值进行排序。我试过这个:

var sorted = unsorted.items.sort(function(a, b) {return a.value - b.value});

alert.log(unsorted);
alert.log(sorted);

但问题是我有另一个字段不是 json "selected_year": 2015 并且它发出错误 TypeError: Cannot read property 'sort' of undefined

不知道怎么办?这是我的 JSFIDDLE

更新:我想对“年”内的数组进行排序,所以我得到了:

var sorted = {
"2014": [
{
"title": "Cheese",
"value": 2

},
{
"title": "Book",
"value": 10
}
],
"2015": [
{
"title": "Movie",
"value": 9
}
],
"2016": [
{
"title": "Back",
"value": 22
},
{
"title": "Slay",
"value": 90
}

],
"selected_year": 2015
};

例如在排序后的“2014”里面我有:

"2014": [
{
"title": "Cheese",
"value": 2

},
{
"title": "Book",
"value": 10
}
]

最佳答案

您只能对数组属性进行排序:

var unsorted = {
"2014": [
{
"title": "Book",
"value": 10
},
{
"title": "Cheese",
"value": 2
}
],
"2015": [
{
"title": "Movie",
"value": 9
}
],
"2016": [
{
"title": "Slay",
"value": 90
},
{
"title": "Back",
"value": 22
}
],
"selected_year": 2015
};

var sorted = Object.assign({}, unsorted); // Copy the unsorted object

Object.keys(sorted).forEach(key => {
if (Array.isArray(sorted[key])) {
sorted[key].sort((a, b) => a.value - b.value);
}
})

console.log(sorted);

关于javascript - 在 JSON 对象中排序数组给出 TypeError : Cannot read property 'sort' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47750347/

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