9

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
  • This is not JSON, look at how JSON should be formatted Commented Oct 1, 2014 at 6:49

2 Answers 2

16

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");
Sign up to request clarification or add additional context in comments.

4 Comments

why is it when I do console.log(json) after the call, the JSON isn't sorted? What am I misunderstanding?
functions? sortBy and pluck return values; neither operates on in-place data.
I must be missing something. I want to say json = _.sortBy(json, "key"); console.log(json); At that point, I need the results to be sorted. For some reason, they're still not sorted using the approach listed above.
@StephenThomas how can I re arrange the array json itself instead of pluck, meaning returning a sorted new array
4
_.map(_.sortBy(json, 'key'), 'value');

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.