Analyzing and tallying JSON attributes using JavaScript

I have a JSON object with items that I need to analyze in JavaScript. When I view the JSON in the console, there is an element called items that contains an array of relevant information.

console.log(json)


{current_page: 1, per_page: 100, total_entries: 106, items: Array(100)}
current_page:1
items:Array(100)
0:{id: 15814, name: "Vehicle_1001", state: "available", repair_state: "broken", network_id: 99, …}
1:{id: 16519, name: "Vehicle_1002", state: "available", repair_state: "broken", network_id: 99, …}

However, when I attempt to use the filter function to count the number of records where repair_state is set to broken, I encounter an error:

json.filter(value => value.items.repair_state === 'broken').length

Uncaught TypeError: json.filter is not a function

What am I doing incorrectly and how can I determine the count of items with a repair_state property equal to broken in this scenario?

Answer №1

After reviewing your console.log, it appears that the JSON object contains an array called items. To filter this array, you should apply the filter method to the items array. Here's how you can do it:

var result =   json.items.filter(value => value.repair_state === 'broken').length;

DEMO

var json= {
  "current_page": 1,
  "per_page": 100,
  "total_entries": 106,
  "items": [
    {
      "id": "15814",
      "name": "Vehicle_1001",
      "state": "available",
      "repair_state": "broken"
    },
    {
      "id": "16519",
      "name": "Vehicle_1002",
      "state": "available",
      "repair_state": "broken"
    }
  ]
};

var result =   json.items.filter(value => value.repair_state === 'broken').length;
console.log(result);

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

How come it is not possible for me to choose all elements containing an attribute value saved in a variable?

Imagine you have the following snippet of HTML code: <div data-id=5>...</div> <img data-id=5 src=...> <input data-id=5 ...> ... Your task is to select and remove all elements with the attribute data-id set to 5. Here is one attemp ...

Detecting the Escape key when the browser's search bar is open - a step-by-step guide

One feature on my website is an editor window that can be closed using the Escape key. The functionality is implemented in JavaScript: $(document).keyup( function(e) { // Closing editor window with ESCAPE KEY if(e.which == 27) { // Clic ...

JavaScript function failing to validate password

While engaging in an online game where the objective is to uncover a password by inspecting the page source or element, I encountered a puzzling line: if(el.value == ""+CodeCode+""). My assumption is that el.value represents my guess, and it indicates that ...

Unleashing the power of Sinon: a guide to covertly observing the e

I need to verify if the method "res.render" is invoked with the correct parameters. it("Checks if the page for creating a new user is rendered", done => { const spy = sinon.spy(ejs, "render"); chai .request(app) .get("/users/create ...

Having trouble with the API authentication call, receiving a "Failed to load resource: net::ERR_CONNECTION_REFUSED" error message

I am facing an issue with my Vue and .net application. Whenever I run "NPM start serve," it successfully builds the app. The app is running locally at: http://localhost:8080/ However, when I attempt to log in, I encounter the following error: Console err ...

Steps for returning a res.send(req.body) upon sending back to a function

I'm currently working on sending the req.body from a POST request route back to the executing function for further processing. The structure of req.body is as follows: { username: 'aa', password: 'ss' } After making the post requ ...

A technique for postponing the addition of a class to a div

I am attempting to create a unique type of slider effect. Inside a single div named #slider, I have 9 items displayed in a line. Link to JsFiddle The slider is 1860px wide, but only 620px is visible at any given time due to the parent having an overflow: ...

How can JavaScript routes be used to apply specific code to multiple pages on a website?

Can you provide guidance on how to run the same code for multiple pages using routes? Below is an example I am currently exploring: var routeManager = { _routes: {}, // Collection of routes add: function(urls, action) { urls.forEach(fun ...

Implementing Pagination in Vue: How to Make it Work with Response Data

I am looking to integrate pagination from the response data into my existing code, while also incorporating filters. JavaScript var entriesList = new Vue({ el: "#post-list-template", data: { posts: [], categories: [], cu ...

React and Rails are not playing nice when it comes to AJAX POST requests - all

I'm currently facing an issue while setting up this AJAX POST request in my react component to interact with my rails api controller. The browser console shows a 404 error and I am unable to trigger the pry debugger. react/src/pages/HomeIndex.js ge ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...

Implementing Bootstrap tooltips in content that can be scrolled

I need help with positioning two containers, which you can view in this FIDDLE. Both containers may contain a lot of content, so I have applied overflow: auto to both of them. This is the HTML structure: <div id="maincontainer"> <d ...

Transforming localhost into a server name in a Node.js environment

Recently I began working on full stack development. I have a physical server and I want to upload my code to it so I can run the NodeJS server from there. This way, when people try to access my site, they will use or instead of localhost:port, which on ...

Switch the array's value if the key is a match?

I'm currently facing an issue where my code does not push the object when the key matches. How can I update the value of the key instead when there is a match? this.state.data.concat(items).filter(function (a) { return !this[a.key] && (th ...

Could the php function json_encode() be a security risk if used within a script tag?

A while back, I had read OWASP's XSS Prevention Cheat Sheet and created a wrapper function that included JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP by default to ensure safety. However, a user on Freenode/##php pointed out that this approac ...

Error with XMLHTTPRequest loading in beforeunload/unload event handlers in iOS 13.4.1 encountered

Currently, I am utilizing XMLHTTPRequest for data posting in JavaScript. Previously, it functioned smoothly on Safari and Chrome browsers up to iOS 13.3.1. However, upon updating to the latest OS version, iOS 13.4.1, an error message stating "XMLHTTPReques ...

Is there a way for me to invoke a different function that is located external to

I am currently in the process of setting up an event that triggers on any change within the form input class. import React, { useState } from "react"; DealerRegistration extends React.Component { state = { business_type : 'd ...

Keep the user on the current page even after submitting the parameter

I have a situation where I am loading a page into a specific div. This loaded page contains a link that includes a parameter which directs to another page for deletion. However, when I click on the loaded page within the div, it redirects me to the deletio ...

Guide to deserializing JSON with a dynamically changing root key

I am having difficulties working with this JSON data. {"1234345": [{ "queue": "XXX", "name": "XXXXX", "entries": [{ "points": 54, "isInactive": false, }], "tier": "ASDF" }]} However, the JSON data can also have a different structure: ...

Guide to retrieving multiple book search results through the Google Books API

Currently, I am utilizing the Google Books API to retrieve search results with multiple books. Below is my implementation: def lookup(search): """Look up search for books.""" # Contact API try: url = f&apos ...