使用LoDash对Json数组进行排序 [英] Sort Json Array with LoDash

查看:292
本文介绍了使用LoDash对Json数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON数组,其一般结构如下:

I have a JSON array whose general structure is like this:

var json = [ 
  { key: 'firstName', value: 'Bill' },
  { key: 'lastName',  value: 'Mans' },
  { key: 'phone', value: '123.456.7890' }
];

实际上,会有更多的键/值对。无论哪种方式,我都试图使用 Lodash 按键值对此数组进行排序。目前,我正在尝试以下方法:

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:

_.map(_.sortBy(json, key), _.values);

然而,这会导致错误:

[ReferenceError: key is not defined]

I怀疑是因为密钥没有用引号括起来,如 docs 所示。不幸的是,我实际上并没有控制json的格式。实际上它被其他开发者使用,我是最后一个使用它。有没有办法让我使用lodash按键名对json数组进行排序?如果是这样,怎么样?

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?

谢谢

推荐答案

你需要只有在调用 sortBy 时才将密钥放在引号中。它不必在数据本身的引号中。

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(json, "key")

此外,你的 map 的第二个参数是错误的。它应该是一个函数,但使用 pluck 更容易。

Also, your second parameter to map is wrong. It should be a function, but using pluck is easier.

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

这篇关于使用LoDash对Json数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆