如果我有这样的东西:
var lowestPricesCars =
{
HondaC:
{
owner: "",
price: 45156
},
FordNew:
{
owner: "",
price:4100
},
HondaOld:
{
owner: "",
price: 45745
},
FordOld:
{
owner: "",
price: 34156
},
}
如何根据价格订购汽车?
如果问题不清楚,请注释掉。
谢谢
答案 0 :(得分:1)
const arrayOfKeys = Object.keys(lowestPricesCars)
const keysSortedByPrice = arrayOfKeys.sort((a,b) => {
return lowestPricesCars[a].price - lowestPricesCars[b].price;
});
let carsSortedByPrice = {}
keysSortedByPrice.forEach(key => carsSortedByPrice[key] = lowestPricesCars[key])
如果要撤消订单:
return lowestPricesCars[b].price - lowestPricesCars[a].price;
答案 1 :(得分:0)
您可以通过 ES6 Object.entries
,Array.sort
和Array.reduce
以简洁的方式进行操作。
但是不能保证对象的键顺序,并且浏览器之间的键顺序不一致,因此不建议使用该键。
const data = { HondaC: { owner: "", price: 45156 }, FordNew: { owner: "", price:4100 }, HondaOld: { owner: "", price: 45745 }, FordOld: { owner: "", price: 34156 } }
console.log(Object.entries(data)
.sort((a,b) => a[1].price - b[1].price) // for DESC b[1].price - a[1].price
.reduce((r,[k,v]) => (r[k] = v, r), {}))