Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.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
Sorting 由对象列表分类的Lodash卡在包装器中__Sorting_Lodash - Fatal编程技术网

Sorting 由对象列表分类的Lodash卡在包装器中_

Sorting 由对象列表分类的Lodash卡在包装器中_,sorting,lodash,Sorting,Lodash,我正在试验lodash分类。我得到了对对象列表进行排序的lodash,尽管排序结果被困在包装器中。如果使用.value(),则会得到未排序的键输出 var testData = {c:1,b:2,a:3} var sortedKeys = _(testData).keys().sortBy(key => {return testData.key}); console.log(sortedKeys); 将产生: LodashWrapper {__wrapped__: {…}, __act

我正在试验lodash分类。我得到了对对象列表进行排序的lodash,尽管排序结果被困在包装器中。如果使用.value(),则会得到未排序的键输出

var testData = {c:1,b:2,a:3}

var sortedKeys = _(testData).keys().sortBy(key => {return testData.key});
console.log(sortedKeys);
将产生:

LodashWrapper {__wrapped__: {…}, __actions__: Array(2), __chain__: false, __index__: 0, __values__: undefined}
__actions__:(2) [{…}, {…}]
__chain__:false
__index__:0
__values__:undefined
__wrapped__:
            a:3
            b:2
            c:1
__proto__:Object
__proto__:lodash

为了从lodash包装器中获得已排序的对象列表,我缺少了什么。

当您执行
testData.key
时,我非常确信您实际上是在执行
testData[key]

仅此一点就允许该方法正常工作,即返回按值排序的对象键数组。请注意,如果要展开lodash对象,仍然必须调用
.value()

如果您还有其他期待,请澄清

const testData = {c:1,b:2,a:0}

const sortedKeys = _(testData).keys().sortBy(key => {return testData[key]})
/* can do without the return like the below as well */
// const sortedKeys = _(testData).keys().sortBy(key => testData[key])

console.log(sortedKeys.value())
// produces ['a','c','b']
如果需要密钥和值对,请尝试下面的方法

_(obj).toPairs().sortBy(0).value()

我认为这里发生的几件事值得注意:

首先,使用for the lodash方法启动排序语句,该方法允许一个操作的结果流入下一个操作。这类似于
lodash/fp
中的流的工作方式

链接要求链中的最后一个操作以
values()
结束,以便从lodash包装器获得实际结果。因此,如果你这样做了:

_(testData).keys().sortBy(key => {return testData.key}).values(); // OR
_.chian(testData).keys().sortBy(key => {return testData.key}).values();
你会得到一些结果

第二个问题是,在您的流中,您获得了对象的键,但实际上并没有按它们排序。要做到这一点,您需要以下内容:

var testData={c:1,b:2,a:3}
log(u.chain(testData.keys().sortBy().value())

感谢您的回复,尽管我正在尝试提取“key:value”对作为答案=>{a:3,b:2,c:1}。另外,testData[key]和testData.key返回相同的答案no
testData[key]
testData.key不同,其中key是定义的变量。我编辑了我的答案,以包含一个显示有序元组的方法。假设testData是这样初始化的对象:
var testData={key:'akey',prop:'aprop'}
。当您说
console.log(testData.key)时
您将在控制台中获得
'akey'
,但当您说
var key='prop';log(testData[key])您将获得
'aprop'
。这就是两者的不同之处。