_lodash orderBy()和sortBy()根据属性' weight'

时间:2017-08-22 10:03:48

标签: javascript arrays json object lodash

对于那些已投票(负面)的人,我展示了我需要的东西!

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()

e.g。 :_.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等。

任何人都可以伸出援手吗?感谢。

1 个答案:

答案 0 :(得分:0)

看看这对你有帮助。如果需要,您可以删除额外的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);