Order JSON Array Using LoDash Library

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.

Answer №1

Remember to enclose the key in quotes only when using sortBy. It is not necessary to have the key in quotes within the data itself.

_.sortBy(json, "key")

Furthermore, ensure that your second parameter for map is a function. An alternative method is to utilize pluck, which simplifies the process.

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

Answer №2

Sort and map the 'json' object by 'key' field using lodash: _.map(_.sortBy(json, 'key'), 'value');

IMPORTANT: Please note that _.pluck has been removed from the latest version of lodash. Use _.map instead as a suitable alternative.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting JSON data to a different JSON format through JOLT Transformation

I am a newcomer to JOLT and finding myself stuck with this specific requirement. I have looked at some examples online, but none seem to fit my unique structure needs. Hopefully, someone will be able to understand what I am trying to convey. Input JSON [ ...

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

Retrieve information using an AJAX call

There is JSON data stored in a file that I need to read. The correct file data is printed to the console.log. What steps should I take to assign this data to variable x? Currently, when I execute the code, x ends up being undefined. function getData() { ...

Automatically tally up the pages and showcase the page numbers for seamless printing

I've been tackling a challenge in my Vue.js application, specifically with generating invoices and accurately numbering the pages. An issue arose when printing the invoice – each page was labeled "Page 1 of 20" irrespective of its actual position in ...

Guide to generating interactive material-ui components within a react application?

I am facing a challenge in creating a dynamic mui grid element triggered by a button click in a React component. When attempting to create let newGrid = document.createElement('Grid'), it does not behave the same way as a regular div creation. D ...

Is there a way in JavaScript to convert a web page into a string?

I'm looking for a way to retrieve the HTML content of a webpage using JavaScript, even if it's on a different domain. Similar to what wget does but in JavaScript. I intend to use this for web crawling purposes. Could anyone guide me on how to fe ...

Unit Testing JWT in Angular 2

Using JWT for authentication in my API calls. I am in the process of coding a service method. An interceptor is applied to all requests: public interceptBefore(request: InterceptedRequest): InterceptedRequest { // Modify or obtain information from ...

Enhancing the appearance of HTML code within x-template script tags in Sublime Text 3 with syntax highlighting

I recently updated to the latest version of sublime text (Version 3.1.1 Build 3176) and have encountered a problem with syntax highlighting for HTML code inside script tags. Just to provide some context, I'm using x-template scripts to build Vue.js c ...

Looking for a JSON file in bash?

I have a JSON file that I need to extract a specific part from: { "expand": "names,schema", "issues": [ { "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields", "fields": { ...

What is the best way to combine database table data based on two columns and then display it as a json

I am having some difficulty retrieving JSON data from PhpMyAdmin (MySQL). The desired format is: [{ “converterno”: ”1”, “zoneno”: {“1a”, “codeid”:[“t1”,”t2”,”t3”]}, “zoneno”: {“1b”, “codeid”:[“t21”,”t0”, ...

Troubleshooting: Issue with displaying PHP data on an AngularJS table using JSON through jQuery AJAX

I've been encountering an issue while trying to display data from a database on my HTML page using Angular and JSON. Despite the browser being able to read the database, it fails to show the data. Can anyone shed some light on why this might be happen ...

Using Java to consume GraphQL queries

I have a Graphql query that is structured like this: query { priceData { customer id title dob } } When using this query in Java, it is typically represented as a String like this: "{\"query\":\"que ...

I'm encountering difficulties in utilizing Ajax to upload images

I have been attempting to utilize ajax and bootstrap (modal) to add a new product. However, when I click the save changes button, I encounter an issue where all fields return an error message stating 'Undefined index'. Below is the code snippet ...

Why does jQuery val() function fail to clear readonly input date in Firefox but succeed in Chrome?

When using JQuery.val(''), I noticed a difference in behavior between Firefox and Chrome. You can see the issue demonstrated in this jsfiddle: https://jsfiddle.net/mdqfbj/d4eovkg8/3/ A JS function triggered by a radio button is supposed to clea ...

Using Javascript, when the command key is pressed, open the link in a new window

Currently, I am working on a Javascript function that opens links in a new tab only when the "command" key is pressed on an Apple computer. Here is what I have so far: $(document).on('click','a[data-id]',function(e){ if(e.ctrlKey|| ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

Creating a JSON representation of a many-to-many model in Django

I am working with a Django model that includes a Rule class and a Module class. The Rule class has attributes such as name, user, threshold, alert_value, and is_internal. While the Module class has attributes like name, description, is_internal, and rules ...

When the Ajax "GET" request is made to the intra-service, the CMS service worker will respond with an "OK" even when offline

Hello there, We are currently utilizing an open-source CMS that recently received an upgrade with a new feature - a javascript serviceworker implementation to manage all requests. This CMS includes workflow forms where users engage (created by us). Durin ...

the navigate feature is not redirecting to the intended page as expected

I am currently working on a React application and facing an issue with configuring the navigation. The problem lies in the code of the Navbar component, where upon clicking the logout button, the authentication context should be cleared and the user should ...

Printing content to an HTML page using Node.js

I'm seeking advice on using Node JS, AJAX, and other related technologies. My goal is to display the content of a JSON file on my HTML page. While I've been successful in saving new objects to the JSON file, I'm struggling to find an effecti ...