Javascript _lodash orderBy()和sortBy()基于属性对对象进行排序';重量'; 对于那些已经投了反对票的人,我展示了我所需要的!
现场链接: 请先学习再判断。 我有这样一个对象数组:Javascript _lodash orderBy()和sortBy()基于属性对对象进行排序';重量'; 对于那些已经投了反对票的人,我展示了我所需要的!,javascript,arrays,json,object,lodash,Javascript,Arrays,Json,Object,Lodash,现场链接: 请先学习再判断。 我有这样一个对象数组: 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}, } 运行时:\uu.orderBy或\uu.sortBy() e、 g.:\u.orderBy(obj,['weight']) 我得到排序数
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},
}
运行时:\uu.orderBy或\uu.sortBy()
e、 g.:\u.orderBy(obj,['weight'])
我得到排序数组,但没有初始键
0: {name: "eee", weight: 1}
1: {name: "ddd", weight: 2}
2: {name: "ccc", weight: 3}
3: {name: "aaa", weight: 4}
但我需要原始密钥项目1、项目2等
有人能帮忙吗?谢谢。看看这是否对你有帮助。如果需要,您可以删除额外的
键
属性
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);
不能对对象进行排序。对象在javascript中本质上是不排序的。如果要保留原始键,可以将它们作为属性保存在内部对象中。您希望初始键如何位于新数组中?您希望新数组如何按权重、名称、键进行排序?而不是用0,1,2,3替换键。请保留项_1、项_2、项_3&item_4@TheoItzaris它不是“用0,1替换键”,而是创建新数组,因为不能有具有排序属性的普通对象。规范不保证键的顺序。所以你不应该依赖它。@YuryTarabanko是对的,你不能在一个对象中有排序属性。阅读本文了解更多信息:没有人,我实现了我所需要的。1.获取对象。2.将其转换为数组3。把它分类。将其转换回具有已排序属性的对象。我在末尾返回object,这是最难的部分:console.log(sortedObj)返回一个数组。
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);