javascript 使用 LoDash 对 Json 数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23396469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort Json Array with LoDash
提问by user3469584
I have a JSON array whose general structure is like this:
我有一个 JSON 数组,它的一般结构是这样的:
var json = [
{ key: 'firstName', value: 'Bill' },
{ key: 'lastName', value: 'Mans' },
{ key: 'phone', value: '123.456.7890' }
];
In reality, there will be a lot more key/value pairs. Either way, I'm trying to sort this array by the key value using Lodash. Currently, I'm trying the following:
实际上,会有更多的键/值对。无论哪种方式,我都试图使用Lodash按键值对这个数组进行排序。目前,我正在尝试以下操作:
_.map(_.sortBy(json, key), _.values);
However, that causes an error that says:
但是,这会导致一个错误,指出:
[ReferenceError: key is not defined]
I suspect its because key is not wrapped in quotes as shown in the docs. Unfortunately, I do not actually have control over the format of the json. In reality its being used by other developers and I'm the last to use it. Is there a way for me to sort the json array, by key names, using lodash? If so, how?
我怀疑是因为 key 没有用引号括起来,如文档中所示。不幸的是,我实际上无法控制 json 的格式。实际上它被其他开发人员使用,而我是最后一个使用它的人。有没有办法使用 lodash 按键名对 json 数组进行排序?如果是这样,如何?
thank you
谢谢
回答by Stephen Thomas
You need to put the key in quotes only when calling sortBy
. It doesn't have to be in quotes in the data itself.
只有在调用sortBy
. 它不必在数据本身中用引号引起来。
_.sortBy(json, "key")
Also, your second parameter to map
is wrong. It should be a function, but using pluck
is easier.
另外,您的第二个参数 tomap
是错误的。它应该是一个函数,但使用起来pluck
更容易。
_.pluck( _.sortBy(json, "key") , "value");
回答by Jeremy Moritz
_.map(_.sortBy(json, 'key'), 'value');
NOTE: In the latest version of lodash, _.pluck
no longer exists. Use _.map
instead as a drop-in replacement
注意:在最新版本的 lodash 中,_.pluck
不再存在。使用_.map
,而不是作为一个下拉更换