How to Sort JSON Data Based on Property in JavaScript

I've got a serialized JSON collection:

[
    {
        "_id":"person1",
        "date":"7/20/2014 17:20:09",
        "listed_name":"Tom",
        "name":"Tom",
        "contact_info":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0a11133e19131f1712501d1113">[email protected]</a>"
    },
    {
        "_id":"person2",
        "date":"7/20/2014 17:20:09",
        "listed_name":"Jane",
        "name":"Jane",
        "contact_info":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8bdbeef9f8e4e5b9cbece6eae2e7a5e8e4e6">[email protected]</a>"
    },
    {
        "_id":"person3",
        "date":"7/20/2014 17:20:09",
        "listed_name":"John",
        "name":"John",
        "contact_info":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14447166677b7a27547379757d783a777b79">[email protected]</a>"
    }
]

On another page, there is property name information...

["_id", "date", "listed_name"]

The question at hand is...

Using JavaScript, how can I filter the JSON objects to only display columns specified in the second array?

For example: if using this array ["_id"]... how might one use it as a filter to show only the _id data but exclude date, listed_name, name, etc... for all objects?

When filtering with ["_id"] array, the expected console output should be as follows:

person1
person2
person3

Answer №1

Assume you have the JSON data stored in a variable.

var jsonData = JSON.parse(incomingData)
var filterKeys = ["name", "age"]

for (var j = 0; j < jsonData.length; ++j) {
    for (var key in filterKeys) {
        console.log(jsonData[j][filterKeys[key]])
    }
}

Answer №2

If you create a small helper function called select (or utilize underscore's _.select) to choose specific properties from an object, then in ES6 it can be written simply as:

input . map(element => select(element, fields))

In simpler terms, elaborated with emphasized words related to the code snippet above:

Take the input and map each element within it to the result of selecting from that element certain specified fields.

Alternatively, using array comprehensions:

[ for (elt of input) select(elt, fields) ]

Or in ES5:

input . map(function(elt) { return select(elt, fields); })

How do you implement the select function? In ES6, you can define it like this:

function select(o, fields) {
    return Object.assign({}, ...(for (p of fields) {[p]: o[p]}));
}

Refer to One-liner to take some properties from object in ES 6 for more insights. The question also suggests non-ES6 alternatives, such as:

function select(o, fields) {
    return fields.reduce(function(result, field) {
        result[field] = o[field];
        return result;
    }, {});
}

Answer №3

To simplify the array, I would deserialize it first and utilize the .map method to iterate over each item in the array of identifiers that need to be preserved. Then, I would create a new object by copying these identifiers and returning it within the map function. In basic code terms:

var filters = [/* list of identifiers to preserve */];
var filtered = JSON.parse(unfiltered).map(function(currObj) {
  var temp = {};
  for identifier in filters:
    temp[identifier] = currObj[identifier];
  return temp;
});

This process will result in an array of objects that have been filtered and stored in the variable filtered.

Answer №4

Appreciate the assistance from everyone, but I managed to find a solution. It may not be the most efficient, but it does the job. Below is the complete code:

    $.getJSON( '/jsonData', function(data) {

            //Storing JSON list data in a variable.
            var listData = data;
            //Getting external query array.
var parsedArray = JSON.parse([storedArray]); //output displayed on console:["_id", "date", "listed_name"]
//Looping through parsedArray to retrieve filters.
for(var i=0;i<parsedArray.length;i++){
    //Assigning array items to a variable.
    var queryKeys = parsedArray[i];
    //Iterating over all JSON data.
    for(var x=0;x<ListData.length;x++){
        //Filtering output by using the queryKeys variable.
        console.log(makerListData[x][queryKeys]);
    }
});

Output on console:

person1
person2
person3
7/20/2014 17:20:09
7/20/2014 17:20:09
7/20/2014 17:20:09
Tom
Jane
John

Answer №5

If you don't mind using a library, lodash can simplify this process:

function selectAttributes(collection, attributes) {
  return _(attributes)
    .map(function(attr) { return _.pluck(collection, attr); })
    .flatten()
    .value();
}

Examples:

selectAttributes(data, ['_id']);
// -> ["person1", "person2", "person3"]

selectAttributes(data, ['_id', 'date', 'listed_name']);
// -> ["person1", "person2", "person3", "7/20/2014 17:20:09", "7/20/2014 17:20:09", "7/20/2014 17:20:09", "Tom", "Jane", "John"]

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

VueJS - Input Image Display Issue Causing Browser Slowdown

I'm experiencing some issues with my VueJS component that includes a file input and displays an image afterwards. Strangely, this is causing my web browsers (both Firefox and Chromium) to freeze up and use massive amounts of CPU. I tried switching to ...

Error Notification Regarding Java Array Operations

Similar Question: ArrayIndexOutOfBoundsException Is there a way to prevent the display of this error message? The error message is shown as: Error in thread "main" java.lang.ArrayIndexOutOfBoundsException at Test.main (Test.java:28 ) This error occ ...

Is there a tool that can help pinpoint the original collection for shared elements across multiple collections?

When given multiple collections/arrays, I am interested in identifying the common elements and which collections they belong to. This request is somewhat similar to this query, but there may be matching elements between collection1 and collection3, or eve ...

Revamping an npm package on GitHub

Currently, I am managing a project that has gained popularity among users and has received contributions from multiple individuals. The next step I want to take is to convert the entire library into TypeScript, but I am unsure of the best approach to ach ...

Is there a different npm package that can extract paragraph data since pdf2json npm package is not working properly?

After attempting to use the pdf2json npm package to extract data from a PDF, I found that it was not extracting the data into paragraphs as desired. I have a PDF document that includes tables, paragraphs, and charts, and I am looking to extract the raw da ...

Center-aligned text animation in CSS3

My custom text includes a CSS3 animation. Check it out on this fiddle: http://jsfiddle.net/pwLxo78k/ In the animation, one part of the text ("I love") remains static while the other part changes dynamically. I'm trying to center my text while ensuri ...

Concealing a div based on empty textboxes using backbone and javascript

I need assistance with displaying or hiding a div based on the length of text boxes. My project is structured using Backbone, so I am unsure about where to insert the code.. Here is my current code; <input type="text" id="txtUsername" placeholder="use ...

Getting the Nth Keys from a Struct in Python

I have a JSON with nested structs or lists, and I need to extract all the nth keys from it after parsing through them. While I have managed to do this recursively in Python, I am looking for help on how to solve this iteratively. Any assistance with this p ...

Issues occurring with PhoneGap preventing the execution of AngularJS code

I've recently delved into learning AngularJS with PhoneGap and I have a basic HTML code along with some AngularJS snippets. While everything runs smoothly in the browser, only the HTML portion seems to work when I attempt to run it on my Android phone ...

Is it possible to initialize an array literal using variables in the C programming language?

I've been trying to figure out if it's possible to initialize an array literal with variables, but I haven't found a definitive answer. Just to give some context, my goal is to pass an array literal to a function. Here's the code snippe ...

Halting Execution After Placing an Object in Three.js Scene with Javascript

It seems like a simple task, but I've been struggling with it for days. How can I add objects to a scene with a pause between each addition? Inside a loop{ I call the make_obj function() then I call the wait function() } The issue is that the pr ...

What is the best way to include a class in the <td> element of a dynamic table?

My goal is to sum up the values in a specific column of a dynamic table by attaching an id property to each row. I am specifically focused on assigning an id to each <td> in every row of the table. UPDATE: Although I have all 4 keys in the <td> ...

Error encountered due to an unset offset on an array that was previously displayed?

I am encountering an issue with the behavior of my code. Within a loop, I am checking if the array contains an 'data' index. If it does not exist, I attempt to identify the previous, next, and current values in the array. What is confusing me is ...

It is not possible for AngularJS to retrieve values using ng-model when ng-repeat is being used

Is there a way to capture dynamically generated data using ng-model (data created with ng-repeat) so that I can send it as an object to Firebase, my flat database? Currently, the ng-model is only retrieving empty strings as values. Any ideas for a solution ...

What is the best way to retrieve a list of unchecked checkboxes in a Razor Page model?

Currently, I am working on a razor page using .NET Core 7. I have encountered an issue where I am unable to pass values of 1, 2, and 3 for unchecked checkboxes from the HTML page to the page model in the post method. When the user clicks the submit button ...

What is the best way to extract information from a text file and store it in an array of structures?

Looking to retrieve information from a file named fields.txt that contains data about the members of the struct Fields. {1, 0, 7.4, 39.5, 5.33784}, {3, 1, 4.6, 27.9, 6.06522}, {5, 2, 2.2, 12.5, 5.68182}, {8, 0, 14.5, 86, 5.93103}, {11, 1, 8, 43.8, 5.4 ...

The output returned by the `reduce()` method cannot be displayed in HTML within a React component when using the `map()` function

Here is the output I am getting: https://i.sstatic.net/E4fK7.png It was generated by the code snippet below: var allblogs = [{ "banner": "41173047269_1594284317134_88820381534.png", "approved_status": 1, "posted_month": "July", "posted_ ...

Creating a distinctive vue form component from scratch

I have a requirement to develop a Vue component that enables users to create or edit a mailing address. The existing component structure is as follows: <template> <v-container> <v-form ref="form" lazy-validation> <v-text-field ...

Exploring the jQuery Solution for Enhancing Dojo Widget Framework

My experience with Dojo in the past has been great, especially with its widget infrastructure. Being able to easily separate code and HTML content, having a seamless connection with the require system used by Dojo, and the convenient builder that compresse ...

What is the name of the event triggered when a jQuery UI draggable element is reverting back to its original position?

I am currently using jQuery UI to create a draggable element on my website. I have added a function to the drag event that continuously tracks the position of the element while the user is dragging it. Additionally, I have set revert: true on this element ...