Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top