Sort Json Array with LoDash

不问归期 提交于 2019-12-01 01:47:11

问题


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' }
];

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

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?

thank you


回答1:


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

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

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



回答2:


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

NOTE: In the latest version of lodash, _.pluck no longer exists. Use _.map instead as a drop-in replacement



来源:https://stackoverflow.com/questions/23396469/sort-json-array-with-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!