Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript _lodash orderBy()和sortBy()基于属性对对象进行排序';重量'; 对于那些已经投了反对票的人,我展示了我所需要的!_Javascript_Arrays_Json_Object_Lodash - Fatal编程技术网

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