简体   繁体   English

使用LoDash对Json数组进行排序

[英]Sort Json Array with LoDash

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 . 无论哪种方式,我都试图使用Lodash按键值对此数组进行排序。 Currently, I'm trying the following: 目前,我正在尝试以下方法:

_.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. 不幸的是,我实际上并没有控制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? 有没有办法让我使用lodash按键名对json数组进行排序? If so, how? 如果是这样,怎么样?

thank you 谢谢

You need to put the key in quotes only when calling sortBy . 只有在调用sortBy时才需要将键放在引号中。 It doesn't have to be in quotes in the data itself. 它不必在数据本身中引用。

_.sortBy(json, "key")

Also, your second parameter to map is wrong. 另外,你要map的第二个参数是错误的。 It should be a function, but using pluck is easier. 它应该是一个功能,但使用pluck更容易。

_.pluck( _.sortBy(json, "key") , "value");
_.map(_.sortBy(json, 'key'), 'value');

NOTE: In the latest version of lodash, _.pluck no longer exists. 注意:在最新版本的lodash中, _.pluck_.pluck不再存在。 Use _.map instead as a drop-in replacement 请使用_.map作为替代品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM