Utilizing JavaScript to sift through JSON data

Looking to efficiently parse a large JSON file based on its values.

This is an excerpt from my extensive JSON code (with over 1000 entries).

var jsonObject = [  
   {  
      "UserId":10259,
      "FullName":"hello world",
      "CustomerId":"10165"
   },
   {  
      "UserId":10405,
      "FullName":"test value",
      "CustomerId":"10261"
   },
   {  
      "UserId":10400,
      "FullName":"mark ant",
      "CustomerId":"10161"
   },
   {  
      "UserId":16224,
      "FullName":"jhon cena",
      "CustomerId":""
   },
   {  
      "UserId":10416,
      "FullName":"shoze ahh",
      "CustomerId":"1"
   },
   {  
      "UserId":10244,
      "FullName":"kajal man",
      "CustomerId":"10"
   }
];

In order to filter the JSON object above, I created the following filtering function.

function getUsersBasedOnIDs(CustomerIds) {
    if (CustomerIds == "") {
        console.log(jsonObject);
    } else if (CustomerIds == "9999xx") {

        let result = jsonObject.filter(c => c.CustomerId == "");
        console.log(result);
    } else {
        let result = jsonObject.filter(c => c.CustomerId != "" && CustomerIds.includes(c.CustomerId));
        console.log(result);
    }   
}

Here's how you can call the function:

getUsersBasedOnIDs("");
getUsersBasedOnIDs("10261,10165");
getUsersBasedOnIDs("9999xx"); 

Identified issues with the current implementation include:

  1. The function is not compatible with IE 11 and earlier versions

  2. When calling the function with parameters like usersBasedOnIDs("10261,10165"); or usersBasedOnIDs("10261");, it returns multiple JSON outputs instead of one specific output

    {UserId: 10405, FullName: "test value", CustomerId: "10261"}
    {UserId: 10416, FullName: "shoze ahh", CustomerId: "1"}
    {UserId: 10244, FullName: "kajal man", CustomerId: "10"}

Ideally, the expected output should be just:

{UserId: 10405, FullName: "test value", CustomerId: "10261"}

To address these issues and achieve the desired results, revisions to the function are necessary.

Answer №1

The string "10261,10165" contains 10261, as well as the substrings 1 and 10. That's why those IDs are being filtered as well.

To address this issue, you can first split the string at , to create an array of customer IDs, and then use Array#includes.

const array=[{"UserId":10259,"FullName":"hello world","CustomerId":"10165"},{"UserId":10405,"FullName":"test value","CustomerId":"10261"},{"UserId":10400,"FullName":"mark ant","CustomerId":"10161"},{"UserId":16224,"FullName":"jhon cena","CustomerId":""},{"UserId":10416,"FullName":"shoze ahh","CustomerId":"1"},{"UserId":10244,"FullName":"kajal man","CustomerId":"10"}]

function usersBasedOnIDs(CustomerIds) {
    if (CustomerIds === "")
        return array;
    
    if (CustomerIds == "9999xx")
      return array.filter(c => c.CustomerId == "")
    
   const ids =  CustomerIds.split(",");
   return array.filter(c => c.CustomerId !== "" && ids.includes(c.CustomerId));
}

console.log(usersBasedOnIDs("10261,10165"))
console.log(usersBasedOnIDs("10261"))

Keep in mind that IE11 does not support arrow functions, String#includes, or Array#includes. You can switch your arrow function to:

array.filter(function(c) {
  return c.CustomerId == ""
})

And

Consider using a polyfill for Array#includes and String#includes

Answer №2

Here is the complete solution for compatibility with IE 11, inspired by @adiga's response. The arrow function has been replaced with a normal function and Array.indexOf is used instead of includes.

const array = [
  { UserId: 10259, FullName: "hello world", CustomerId: "10165" },
  { UserId: 10405, FullName: "test value", CustomerId: "10261" },
  { UserId: 10400, FullName: "mark ant", CustomerId: "10161" },
  { UserId: 16224, FullName: "jhon cena", CustomerId: "" },
  { UserId: 10416, FullName: "shoze ahh", CustomerId: "1" },
  { UserId: 10244, FullName: "kajal man", CustomerId: "10" }
];

function usersBasedOnIDs(CustomerIds) {
  if (CustomerIds === "") return array;

  if (CustomerIds == "9999xx") {
    return array.filter(function(c) {
      return c.CustomerId == "";
    });
  }

  const ids = CustomerIds.split(",");
  return array.filter(function(c) {
    return c.CustomerId !== "" && ids.indexOf(c.CustomerId) > -1;
  });
}

console.log(usersBasedOnIDs("10261,10165"))

Answer №3

2 ) It is important to note that IE 11 does not support arrow functions

If you encounter this issue, consider modifying your function to:

var result = jsonObject.filter(function(c) { return c.CustomerId === ""; });

Answer №4

The reason why your code may not function properly in Internet Explorer 11 is due to the use of the includes function to check if an array contains a value. The includes function is only supported in IE 14 and later versions. Additionally, arrow functions are unsupported in IE 11 and earlier.

Your code could be experiencing issues because of a few mistakes. Firstly, the arrow function callback requires a return statement. Instead of:

c => c.CustomerId == ""

You should write:

c => return (c.CustomerId == "")

Furthermore, make sure to pass customer IDs as an array instead of a string. So rather than:

usersBasedOnIDs("10261,10165");

You should do:

usersBasedOnIDs([10261,10165]);

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

Send the contents of a `<ul>` element to the server using AJAX for form submission

Can someone assist me in submitting a serialized <ul> list through an AJAX post form request? I need help with this process. Below is my current code snippet. HTML: <form id="update_fruit_form" method="post" action="/update_fruits" accept-charse ...

The jqGrid displays a plus sign even when the subgrid is empty while using XML

I am utilizing jqGrid to display data with a subgrid in XML format. $("#UDFs").jqGrid({ ajaxGridOptions: { contentType: 'application/xml; charset=utf-8' }, datatype: 'xmlstring', datastr: data, xmlReader: { root: "Respo ...

What is the best way to display a collection of images in an HTML page?

I have a list of strings containing images. How can I display these images on a webpage using Angular? images: [ "https://images.oyoroomscdn.com/uploads/hotel_image/1097/340ea5ee01acc37f.jpg", "https://images.oyoroomscdn.com/uploads/hotel_image/1097 ...

Encountered an Error: Exceeded the number of hooks rendered in the previous render. Any solutions to resolve this issue?

How can I retrieve data from an API using a specific key and display it in a table cell? I attempted the following approach but encountered an error. The issue seems to be related to calling hooks inside loops or nested functions. How should I access the i ...

Looking for help with an ajax request

This is my first time working with $.ajax requests. I am in the process of developing an employee directory that should retrieve information for 12 random individuals like so: https://i.sstatic.net/Ukona.png I have dynamically created 12 gallery cards, w ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

Interacting with wpdb using AngularJS

I just started learning AngularJS and I'm eager to implement it on my WordPress website. My goal is to display a table with data from a database in my WordPress site, but I am encountering difficulties accessing the WordPress functions and variables. ...

The integration of single page applications and <form> elements is a powerful combination in web development

Is there still value in using a <form> element over a <div> element when developing single page applications? I understand the purpose of the <form> element for traditional form submissions with a full page reload, but in the context of ...

What is the best way to remove unicode characters from Python's output?

I'm having trouble loading a JSON file and parsing it in Python 2.7. The output keeps showing 'u' characters, even after trying to open the file with encoding='utf-8'. Is there a simple solution or workaround to remove these ' ...

Am I utilizing window.setInterval correctly in this code, or am I potentially causing issues?

I have a search input with the class .searchinp that is provided by a third party and cannot be modified. However, I want to relocate the search results from the left side of the page to the right side. Currently, I am achieving this by using a setInterval ...

Creating unique error messages for handling JSON requests

Recently, I've been exploring API development using Rails. My main focus right now is ensuring that the correct error messages are displayed based on the incoming request's errors. Currently, I have a straightforward setup: def create @comp ...

Exploring Angular 2 Application Testing: Tips for Interacting with HTML Elements

In my Angular 2 Frontend testing journey, I came across a blog post ( ) where the author utilized ng-test TestBed for core testing in Angular. While the example provided was helpful for basic understanding, it lacked details on how to manipulate Elements. ...

Incorporating Mediainfo.js into Angular 8: A Seamless Integration

I'm attempting to utilize Mediainfo.js for retrieving video information on the frontend of my Angular 8 project. However, I am encountering the following errors: GET https://192.168.25.177:4200/MediaInfoModule.wasm 404 (Not Found) wasm streaming compi ...

GraphQL queries that are strongly-typed

Currently working on a Vue CLI project where I am utilizing axios as my request library. In all the examples I've come across, they use strings for queries like this: { hero { name friends { name } } } Given that I am employing ...

Central alignment of div with cursor

I'm experimenting with creating a unique custom cursor using a <div> that trails the movement of the mouse pointer. While the current setup works smoothly, I've noticed that when scrolling down the page, the div lags behind until the scrol ...

The dynamically generated hyperlink is not displaying correctly

I've been attempting to display a link on my page, but instead of returning the /register path, it immediately redirects to the UTMs.... The href displayed on the site is domain.com/?utm_campaign... rather than domain.com/register?utm_campaign... ...

Tips for updating a specific portion of a component in react.js

import React,{useEffect} from 'react'; import CloudTables from '@cloudtables/react'; import { useState } from 'react'; function DataGridTable ({ input1Value, input2Value }) { return ( <div className="con ...

Pull information from database based on selection made in combo box

I am attempting to populate a text box with values from a database based on the selection in a combo box. I have written the code below but it doesn't seem to be working correctly. The issue is that the value selected in the combo box is not being pas ...

The HTML table inexplicably displays a random comma out of nowhere

When working on my HTML table, I noticed that it was rendering a comma unexpectedly. I am using Nodemailer and SMTP Google server, and I suspect the issue lies within the HTML code. However, I am struggling to identify the exact problem. https://i.stack.i ...

invoking a jquery method through the onClick event handler

How can I make use of jQuery to perform different actions based on which checkbox is clicked? I am encountering an issue where the onClick event is not triggered for any of the checkboxes below. <HTML> <HEAD> <script type="text/javascr ...