简体   繁体   English

使用保存键按属性值对对象的Javascript数组进行排序

[英]Sort Javascript array of objects in place by property value with save keys

How to sort array of objects by property 'cost' with holding string keys? 如何使用持有字符串键的属性“成本”对对象数组进行排序?

Start array : 开始数组:

aparts: {
    apart1 : {id: "1", status: 2, cost: 10033450},
    apart2 : {id: "2", status: 2, cost: 5214000},
    apart3 : {id: "3", status: 2, cost: 7314300},
    apart4 : {id: "4", status: 1, cost: 9261700}    
}

Want to array: 要数组:

aparts: {
    apart2 : {id: "2", status: 2, cost: 5214000},
    apart3 : {id: "3", status: 2, cost: 7314300},
    apart4 : {id: "4", status: 1, cost: 9261700},
    apart1 : {id: "1", status: 2, cost: 10033450}   
}

The order of properties is not guaranteed. 不保证属性的顺序。 See, for example here: 参见例如此处:

https://stackoverflow.com/a/5525820/1250301 https://stackoverflow.com/a/5525820/1250301

If you want something ordered, then you need to use an array. 如果要订购某些东西,则需要使用数组。 The transformation is pretty straightforward: 转换非常简单:

 var aparts = { apart1 : {id: "1", status: 2, cost: 10033450}, apart2 : {id: "2", status: 2, cost: 5214000}, apart3 : {id: "3", status: 2, cost: 7314300}, apart4 : {id: "4", status: 1, cost: 9261700} }; var arr = Object.keys(aparts).map(function(k) { return aparts[k]; }).sort(function(a,b) { return a.cost - b.cost }); console.log(arr); 

 const aparts = { apart1: {id:"1", status: 2, cost: 10033450}, apart2: {id:"2", status: 2, cost: 5214000}, apart3: {id:"3", status: 2, cost: 7314300}, apart4: {id:"4", status: 1, cost: 9261700} }; const arr = Object.keys(aparts) .map(k => (aparts[k])) .sort((a,b) => (a.cost - b.cost)) .map(k => ({["apart" + k.id]: k})) ; console.log(arr); 

I believe you are looking for a Map. 我相信您正在寻找地图。 Which is what your irregular object matches. 这是您的不规则对象匹配的对象。

 let aparts= { apart1: { id: "1", status: 2, cost: 10033450 }, apart2: { id: "2", status: 2, cost: 5214000 }, apart3: { id: "3", status: 2, cost: 7314300 }, apart4: { id: "4", status: 1, cost: 9261700 } }; let sorted = Object.entries(aparts).map(x => Object.assign(x[1], { apart: x[0] })).sort((a, b) => a.cost - b.cost); let result = new Map(sorted.map(x => ([x.apart, (delete x.apart, x)]))); console.log(...result) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM