Combining and organizing two JSON objects

I have three JSON objects that are similar. I want to combine all of them into one list and then sort the entire list based on a specific index value. Here is the description of the objects:

Object 1

[{"link":"#","prod":"Fundamentals Of Software Engineering","price":" Rs. 200 "},{"link":"##","prod":"Real-Time Systems: Theory And Practice","price":" Rs. 394 "}]

Object 2

[{"link":"#","prod":"Fundamentals Of Software Engineering","price":" Rs. 200 "},{"link":"##","prod":"Real-Time Systems: Theory And Practice","price":" Rs. 394 "}] 

Object 3

[{"link":"#","prod":"Fundamentals Of Software Engineering","price":" Rs. 200 "},{"link":"##","prod":"Real-Time Systems: Theory And Practice","price":" Rs. 394 "}] 

After merging them, I would like to sort the combined array based on the price index.

If you have any tips on how to achieve this, please let me know. Thank you :)

Answer №1

To convert JSON strings Object1, Object2, and Object3 into JavaScript objects, utilize the eval function.

After converting them, merge the objects using the concat method. http://www.w3schools.com/jsref/jsref_concat_array.asp

var mergedArray = arr1.concat(arr2, arr3);

Next, sort the merged array using the sort method in JavaScript Array. References: http://www.w3schools.com/jsref/jsref_sort.asp https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

var sorted = mergedArray.sort(function(a, b){

    // Explanation of the sorting process within this function...

    var priceA = parseFloat(a.price.replace("Rs.", ""));
    var priceB = parseFloat(b.price.replace("Rs.", ""));
    return priceA - priceB;

});

For descending order, use return priceB - priceA;. jsfiddle: http://jsfiddle.net/diode/FzzHz/

.

Answer №2

Transform them into objects and try using this method

Answer №3

To combine the arrays, you can utilize the concat method:

var mergedArray = array1.concat(array2, array3);

Following that, you can proceed to sort the newly merged array.

Here is a custom sorting function that sorts based on the prod property (you can choose any property for sorting):

function sortByProd(a, b) {
    var aProd = a.prod.toLowerCase();
    var bProd = b.prod.toLowerCase(); 
    return ((aProd < bProd) ? -1 : ((aProd > bProd) ? 1 : 0));
}

Finally, apply the sorting:

mergedArray.sort(sortByProd);

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

Sending a form from an iPhone device to a PHP backend server

It seems like I'm overlooking a simple aspect... Here is a basic form that I want to submit to a PHP script. It works perfectly on PC and Mac, but it doesn't function properly in Safari on iPad, iPhone, etc. Do you think there's some mobile ...

Incorporating a JSON file through a script element

A customized I18n plugin has been developed to accept various languages through json files. The goal is to simplify usage for users by allowing them to easily insert their json package directly into a page along with the script: <script id="pop-languag ...

Is it possible to implement pagination using 'useSWR' in combination with the contentful-client?

I am currently working on implementing pagination in a Next.js project using the useSWR hook. My approach seems to be functioning correctly, but I have a concern about caching due to the key parameter not being a unique string as recommended in the documen ...

The execution of Node.js callback function is not triggered

After setting up an API that queries a MongoDB and returns JSON Objects, I decided to modularize the code. I moved the MongoDB functionality to a separate file called queryMongo.js, which is now called in the POST request of main.js. Here is the main.js co ...

Is there a way to automatically adjust the size of a 'Pan' popup to fit the View in the ArcGIS JavaScript API?

Has anyone else experienced popups being cut off or out of view in an ArcGIS JSAPI build version 4.26x? I have tried using "view.popup.alignment" and "view.popup.dockEnabled" to control the popup location, but I'm looking for a solution where the view ...

How to pass arguments to the `find` method in MongoDB collections

I've been attempting to pass arguments from a function to the MongoDB collection find method. Here's what I have so far: async find() { try { return await db.collection('users').find.apply(null, arguments); } catch(err) { c ...

Why is it that the function `val()` cannot be used with `$("#id")`?

jsp : <input id="companyName" class="cpn" type="text" value="" ></input> <input id="phoneNumber" class="number" type="text" value=""></input> <textarea id="remark" placeholder="消息备注"></textarea> <input ...

Passing variable values from .post response to PHP: A guide

I'm currently working on integrating Geocode from the Google Maps API into my WordPress plugin within the wp-admin. I have created a custom post type that includes an input field for the address of a place, and I also have jQuery code set up to watch ...

Is there a way for me to display the image name at the bottom before uploading it, and have a new div created every time I upload an image?

Is there a way to display the image name at the bottom and have it create a new div every time an image is uploaded? I would appreciate any help with this... <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstra ...

If the children prop is used to pass a server component to a client component, will it be displayed/rendered on the client side?

The documentation for NextJS explains in this section that all child components and modules imported into a client component are considered part of the client bundle. However, it also mentions the option to mix server and client components by passing a ser ...

What's the most effective method for handling routes and receiving parameters in ExpressJS?

I have created a unique Express.js system where each file in the /routes folder serves as a separate route for my application. For example, /routes/get/user.js can be accessed using http://localhost:8080/user (the /get denotes the method). You can view m ...

Link a distinctive number to a specific element

I am searching for a method to link a DOM element with a distinct number that is not assigned to any other element in the DOM. Using an Id attribute is not an option as not all elements possess such an identifier. One potential approach is to obtain a num ...

Definition of JSON Schema attribute: Field schema not supported for field... : Type of field is undefined

I am in the process of creating a form that is based on a JSON schema and utilizing the react-jsonschema-form component for ReactJS. The purpose of this form is to allow users to input various settings (such as CSS/HTML selectors) that will be used to ext ...

Updating a Tag's Class with the use of getElementsByTagName

I need assistance changing the class of all elements with the 'input' tag using the getElementsByTagName method. I am struggling to successfully modify their classes as my attempts so far have not been fruitful. Any guidance would be greatly appr ...

Utilize MongoDB to store information within a sharding cluster and track the duration of data operations

I am looking to save data on a MonogoDB. For this purpose, I have a setup with one mongos, three configserver, and a sharding configuration consisting of two replicasets (each with primary/secondary/arbiter). There are two main issues I am facing: 1) Wha ...

Creating a Halo (external outline) for a circular sector in THREE.JS

I'm working on adding a halo (external black outline) to certain shapes in three.js. While I was able to achieve this easily with rectangles and circles, I am facing challenges with circular sectors (not full circles). Here is my current attempt: It ...

The content in the div tag isn't showing up properly because of Ajax

I am facing an issue with my Ajax query. Even though I can retrieve the results by posting, they are not displaying in the designated div tag on mainInstructor2.php. Instead, the results are showing up on a different page - specifically, on InstructorStude ...

Res.redirect is failing to redirect and displaying error message 'Connection Unavailable'

Currently, I am in the process of developing a NodeJS + ExpressJS Ecommerce Website. My focus is on enhancing the functionality of the admin panel feature. Users can navigate to /admin/products/new to access a form. When the user completes and submits this ...

Utilizing JSON for Mapping Nested Grails Domain Classes

I'm currently working on a RESTful interface to deliver JSON data for a JavaScript application. For the server side, I am utilizing Grails 1.3.7 and GORM Domain Objects for persistent storage. To properly handle nested domain objects, I have created ...

Saving the id in a variable after triggering an AJAX request by clicking

I attempted to utilize an onClick event within the <a> element but it is not functioning as expected. I am aiming to capture the value 777 into a variable so that I can access it later in the code. My intention was to click on the image and have an ...