id
对它进行排序。
这是我的数据
{
1918: {
id: "1544596802835",
item_id: "1918",
label: "Soft Touch Salt Free Mint 500 ml (000001400045)",
combo_items: false
}
6325: {
id: "15445968134652",
item_id: "6325",
label: "Mirindas Orange Flover 300 ml (012000800160)",
combo_items: false
}
6336: {
id: "15445968106815",
item_id: "6336",
label: "Sting Energy 250ml (012000034220)",
combo_items: false
}
6498: {
id: "1544596806967",
item_id: "6498",
label: "Tido Candy (01)",
combo_items: false
}
7461: {
id: "15445968057103",
item_id: "7461",
label: "Skin Whitening Facial Kit (000051032012)",
combo_items: false
}
}
答案 0 :(得分:2)
首先,您不应该依赖JavaScript对象中的属性顺序(有关详细信息,请参见this question),这意味着您需要将对象排序为数组。
使用Array.prototype.sort()
可以轻松完成此操作:
const sorted = Object.values(data).sort((a, b) => a.id - b.id);
完整代码段:
const data = {
1918: {
id: "1544596802835",
item_id: "1918",
label: "Soft Touch Salt Free Mint 500 ml (000001400045)",
combo_items: false
},
6325: {
id: "15445968134652",
item_id: "6325",
label: "Mirindas Orange Flover 300 ml (012000800160)",
combo_items: false
},
6336: {
id: "15445968106815",
item_id: "6336",
label: "Sting Energy 250ml (012000034220)",
combo_items: false
},
6498: {
id: "1544596806967",
item_id: "6498",
label: "Tido Candy (01)",
combo_items: false
},
7461: {
id: "15445968057103",
item_id: "7461",
label: "Skin Whitening Facial Kit (000051032012)",
combo_items: false
}
};
const sorted = Object.values(data).sort((a, b) => a.id - b.id);
console.log(sorted);
(我修复了对象文字,因为它在属性之间缺少逗号)
答案 1 :(得分:0)
您可以尝试!
function sort(data)
{
return Object.keys(data)
.sort().reduce((a, b) => {
a[b] = data[b];
return a; }, {});
}
const object = {9:"Name 9", 10:"Name 10", 2:"Name 2", 5:"Name 5", 3:"Name 3"};
var sortObject = sort(abject);
结果是
sortObject = {2: "Name 2", 3: "Name 3", 5: "Name 5", 9: "Name 9", 10: "Name 10"}