"Can we apply a filter to the JSON file when it is

I encountered an issue while trying to filter json data based on user selection. The debugger console displayed the error message:

TypeError: obj.contacts.filter is not a function
. I have included a snippet of my code below:

var contactStorage = {};
$("#frm_find").on("submit", findContacts);

function findContacts(e) {
  e.preventDefault();
  var frmFilter = $("#frm_filterby").val();

  if (frmFilter) {
    $.ajax({
      type: "GET",
      url: "https://api.myjson.com/bins/9j7qg?" + new Date().getTime(),
      dataType: "json"
    }).done(function(obj) {
      contactStorage = obj.contacts.filter(function(entry) {
        switch (frmFilter) {
          case '1':
            return entry.status === 1;
            break;
          case '2':
            return entry.status === 0;
            break;
          default:
            return entry;
        }
      });
      console.log(contactStorage);
    }).fail(function(jqXHR, textStatus, errorThrown) {
      alert('Error: ' + errorThrown);
    });
  }
}
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frm_find" id="frm_find" autocomplete="off">
  <div class="row find-row">
    <div class="form-group col-xs-12 ... 
                                </button>
    </div>
  </div>
</form>

If you have any insights on resolving this issue, please share your knowledge. Thank you.

Answer №1

contacts is actually an object, not an array:

contacts:{1: {id: 1, first: "Mike", last: "Johnson", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09d9a9f989e839f9eb0979d91999cde939f9d">[email protected]</a>", phone: "(203) 567-9055",…},…}

If you wish to utilize the filter method, it needs to be converted into an array first. One way to do this is through Object.values:

var contactStorage = {};
$("#frm_find").on("submit", findContacts);

function findContacts(e) {
  e.preventDefault();
  var frmFilter = $("#frm_filterby").val();

  if (frmFilter) {
    $.ajax({
      type: "GET",
      url: "https://api.myjson.com/bins/9j7qg?" + new Date().getTime(),
      dataType: "json"
    }).done(function(obj) {
      contactStorage = Object.values(obj.contacts).filter(function(entry) {
        switch (frmFilter) {
          case '1':
            return entry.status === 1;
            break;
          case '2':
            return entry.status === 0;
            break;
          default:
            return entry;
        }
      });
      console.log(contactStorage);
    }).fail(function(jqXHR, textStatus, errorThrown) {
      alert('Error: ' + errorThrown);
    });
  }
}
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frm_find" id="frm_find" autocomplete="off">
  <div class="row find-row">
    <div class="form-group col-xs-12 col-sm-12 col-md-3 col-md-offset-2 col-lg-3 col-lg-offset-2">
      <select class="form-control" name="frm_filterby" id="frm_filterby" required>
        <option value="">--Choose--</option>
        <option value="1">Active</option>
        <option value="2">Inactive</option>
        <option value="3">Show All</option>
      </select>
    </div>
    <div class="form-group col-xs-12 col-sm-12 col-md-3 col-md-offset-2 col-lg-3 col-lg-offset-2">
      <button class="btn btn-block btn-primary" name="frm_search" id="frm_search">
                                        <span class="glyphicon glyphicon-search"></span> Search
                                    </button>
    </div>
  </div>
</form>

If you intend to transform the filtered array back into an object of some sort, you can use the spread operator:

contactStorage = { ...contactStorage};

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

Can WebSocket messages be encoded?

Is there a way to encrypt or obscure the data I transmit via websockets? For example, the message looks like this: var encryptedMsg = { type: "message", data: { message: "Hello world!" } } I require the ability to send this message in ...

How can I troubleshoot Ajax not loading my additional external JavaScript files?

$(document).ready(function () { $("#livesearch").on("keyup",function(){ var search_term = $(this).val(); $.ajax({ url:"ajax-live-search.php", type:"POST", d ...

Retrieving Data for Specific Key in JSON Object using BigQuery

I am facing a challenge with a string object stored in a table column, having the following structure: [{"__food": "true"},{"item": "1"},{"toppings": "true"},{"__discount_amount": " ...

Guide on sending a JavaScript variable as a URL parameter in Django

I need to pass a radio ID to my view, but I'm struggling with how to do it using the GET method in the URL: html: <a href="{% url 'maintenance_issue_fix' %}?radio_id=checked"> <img src="{% static 'images/ma ...

Encountering an issue in my Next.js application with the app router where I am unable to read properties of undefined, specifically in relation to '

As I develop a basic Rest API in Next.js, my goal is to display "Hello world" in the console for a post api. export const POST = (req: Request) => { console.log('hello world'); }; The error message that appears in my terminal is as follows: ...

I am having trouble with my quiz function as it only checks the answer correctly for the first question. Does anyone have suggestions on how to make it work for

Currently, I'm tackling a quiz project that was assigned to me during my bootcamp. My focus right now is on the checkAnswer function, which evaluates the answer selected by the player. const startButton = document.querySelector(".start") as ...

Refreshing a jsp page without the need to reload the content

On my jsp page, I am displaying the contents of a constantly changing table. This means that users have to refresh the page every time they want to see updated information. Is there a way for me to update the content dynamically without requiring users t ...

Cross-Origin Resource Sharing (CORS) in Ajax requests

I've been attempting to fetch variables from an external domain using AJAX and then populate pre-filled form fields with the retrieved data. However, I'm facing difficulties getting it to function properly. While I'm relatively new to JavaS ...

What causes my JSON file to only allow updates to one field at a time?

Whenever I click the 'Update Button', it triggers an update for a specific field in my JSON file. However, there seems to be an issue: Issue: If I input data into more than one field and then click update, nothing gets updated in the JSON file. ...

(node:19502) UnresolvedPromiseRejectionNotification: Promise rejection not handled (rejection id: 1): TypeError: Unable to access property 'indexOf' of undefined

I successfully integrated cucumber with nightwatch.js. Here is a snippet of my package.json file: { "name": "learning-nightwatch", "version": "1.0.0", "description": "learning nightwatch", "license": "UNLICENSED", "scripts": { "nightwatch": ...

Launching an Angular application from the local server

I have successfully deployed an Angular frontend on a server. It is functioning well, with three scripts: /runtime.0fad6a04e0afb2fa.js /polyfills.24f3ec2108a8e0ab.js /main.a9b28b9970fe807a.js My goal is to start this application in Firefox without ...

What is the correct way to include a MongoDB ObjectId() in the JSON body of an HTTP request

I am in need of sending a mongo query through a JSON typed request body. Something like this: { _id : { $gt : ObjectId("575d0c22964ddb3b6ba41bed") } } This is to retrieve records that were inserted after the specified id'ed record. On the server si ...

What is the process for setting environment variables in a Svelte project?

I'm brand new to working with Svelte and I want to incorporate environment variables like base_url into different components. I've read that I can set up a store to hold these values, for example: const DataStore = writable([ { base_url: & ...

Switching between boolean values based on another value in react is a common practice

When a user is chosen from the list, a boolean value becomes true. If the chosen user is then unselected, the boolean turns false. This boolean will stay true if another user is selected from the list. Here's the code snippet: import React, { useEffec ...

Discovering the magic of activating a JavaScript function on jQuery hover

I need to call a JavaScript function when hovering over an li element. var Divhtml='<div>hover</div>'; $('li a').hover(function(){ $(this).html(Divhtml); //I want to trigger hovercall(); wh ...

Error encountered while converting JSON to CSV due to NoneType issue

Hey everyone, I'm encountering a frustrating 'NoneType' error while trying to parse this particular code block. The issue revolves around the 'Manufacturer' field. Despite my attempts to structure that line in a similar manner to t ...

Can you explain the distinctions among <Div>, <StyledDiv>, and <Box sx={...}> within the MUI framework?

When exploring the MUI documentation, I came across a table of benchmark cases that can be found here. However, the differences between the various cases are not clear to me. Can someone please explain these variances with real examples for the following: ...

Storing images in MongoDB using React.js

I'm currently facing an issue with uploading an image file from the client side to MongoDB. To achieve this, I am utilizing an Express server along with 'multer' and 'sharp' for image uploading. On the client side, I have a CRA a ...

An approach to transferring the ID of a multiple dropdown within the $.each function

function filterFields(classname, value, chkClass) { var checkedfields = []; $.each($("."+classname+" option:selected"), function(){ checkedfields.push($(this).val()); }); $('#'+chkClass+'Filters').val(ch ...

What could be causing my CORS fetch request to not send cookies to the server?

Trying to work out a CORS request using the fetch method: fetch('https://foobar.com/auth', { method: 'GET', mode: 'cors', credentials: 'include', }) The server-side code in express for impl ...