Recently I encountered a JSON array with the following structure:
var json = [
{ key: 'firstName', value: 'Bill' },
{ key: 'lastName', value: 'Mans' },
{ key: 'phone', value: '123.456.7890' }
];
As the array grows, sorting it based on the key values becomes essential. I decided to use Lodash for this task and attempted the following approach:
_.map(_.sortBy(json, 'key'), _.values);
However, an error stating "[ReferenceError: key is not defined]" was thrown. This led me to realize that the key should be wrapped in quotes as mentioned in the documentation. The challenge here lies in the fact that I do not have control over the format of the JSON array, as it is maintained by other developers. Is there a workaround to successfully sort the JSON array by key names using Lodash? If yes, how can I achieve this?
Your assistance is greatly appreciated.