【发布时间】:2018-01-30 13:31:48
【问题描述】:
对于那些已经投票(否决)的人,我展示了我需要的东西!
var obj = {
item_1: {name:'aaa',weight:4},
item_2: {name:'ddd',weight:2},
item_5: {name:'eee',weight:0},
item_3: {name:'ccc',weight:3},
item_6: {name:'ccc',weight:23},
item_4: {name:'eee',weight:1},
}
var arr = _.toPairs(obj)
console.log(arr)
var sortedArr = arr.sort(function(a,b){ return b[1].weight - a[1].weight})
console.log(sortedArr)
var sortedObj = _.fromPairs(sortedArr)
console.log(JSON.stringify(sortedObj))
此处的实时链接:sort Object based on 'weight'property
请先学习再判断。
我有一个像这样的对象数组:
var obj = {
item_1: {name:'aaa',weight:4},
item_2: {name:'ddd',weight:2},
item_3: {name:'ccc',weight:3},
item_4: {name:'eee',weight:1},
}
当我跑步时:_.orderBy or _.sortBy()
例如:_.orderBy(obj,['weight'])。
我得到了排序后的数组,但没有初始键
0: {name: "eee", weight: 1}
1: {name: "ddd", weight: 2}
2: {name: "ccc", weight: 3}
3: {name: "aaa", weight: 4}
但我需要原始键 item_1、item_2 等。
有人可以帮忙吗?谢谢。
【问题讨论】:
-
你不能有排序的对象。对象本质上不是在 javascript 中排序的。如果您想保留原始键,可以将它们作为属性保存在内部对象中。
-
您希望初始键如何位于新数组中?您希望新数组如何按重量、按名称、按键排序??
-
保留item_1、item_2、item_3和item_4而不是用0、1、2、3替换键
-
@TheoItzaris 它不是“用 0、1 替换键”它创建新数组,因为您不能拥有具有排序属性的普通对象。规范不保证键的顺序。所以你不应该依赖它。
-
@YuryTarabanko 是对的,您不能在对象内拥有已排序的属性。阅读本文了解更多信息:stackoverflow.com/questions/5525795/…
标签: javascript arrays json object lodash