【问题标题】:_lodash orderBy() and sortBy() sort object based on a property 'weight'_lodash orderBy() 和 sortBy() 基于属性“权重”排序对象
【发布时间】: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


【解决方案1】:

看看这是否对你有帮助。如果需要,您可以删除额外的 key 属性。

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},
}

function buildItem(item, key) {
    var newItem = { key: key };
    newItem[key] = item;
    return newItem;
}

function byWeight(item) {
    return item[item.key].weight;
}

var arr = _(obj).map(buildItem).sortBy(byWeight).value();
console.log(arr);

【讨论】:

  • 不,我实现了我需要的。 1. 拿到对象。 2. 将其转换为数组 3. 对其进行排序 4. 将其转换回具有已排序属性的对象。我在最后返回对象,这是困难的部分:console.log(sortedObj) 你返回一个数组。
猜你喜欢
  • 2013-01-11
  • 2014-03-06
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
相关资源
最近更新 更多