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

Discover the flawless way to transmit client geolocation to a server. Encounter an intriguing hurdle: Unable to access undefined properties (specifically 'loc') while reading

I encountered an error that says "TypeError: Cannot read properties of undefined (reading 'loc')". This error was triggered when I attempted to pass the user's location to a server through a POST request. In my HTML file, I have included th ...

Create a variety of elements in real-time

My goal is to utilize JavaScript in order to generate a specific number of input boxes based on the user's input. However, I encountered an issue where using a for loop only creates one input box and then appends this same input box multiple times. f ...

Tips for embedding text into a doughnut chart with primeng/chart.js

Currently tackling a primeng chart project involving the development of a doughnut chart within angular. The task at hand is to display text inside the doughnut chart, aligning with the designated design vision. Referencing the image below for visualizatio ...

Learn how to showcase JSON information in a Label within Xamarin forms using the Rest Post Method in an API

{ "status": "SUCCESS", "data": { "userId": "40", "userName": "Madhu", "password": "123456", "fullName": "Balaji", "dateCreated": "2019-08-03 10:36:20", "districtID": "chennai"}} here is my response: ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

The Safari 7.1+ browser seems to be having trouble with the spotlight effect

Why is the CodePen not functioning properly in Safari? Despite working well in Chrome and Firefox, it completely fails to work in Safari 7.1+. Can anyone provide some insights? http://codepen.io/cchambers/pen/Dyldj $(document).on("mousemove", function( ...

Clicking a button in React requires two clicks to update a boolean state by triggering the onClick event

I have a React functional component with input fields, a button, and a tooltip. The tooltip is initially disabled and should only be enabled and visible when the button is clicked and the input fields contain invalid values. The issue I'm facing is t ...

Query to retrieve specific JSON elements

Here is a snippet of JSON data: {"response":[2939, {"mid":6581,"date":1345018696,"out":0,"uid":84175314,"read_state":1,"title":" ... ","body":"Text1"}, {"mid":6578,"date":1344984256,"out":0,"uid":32438192,"read_state":1,"title":" ... ","body":"Text2"} ]} ...

Utilizing Node.js within a closed intranet environment

Utilizing Nodejs's npm has proven to be quite convenient. Thus, I made the decision to incorporate it into my company's project. However, a predicament arises as my company mandates development within a closed network. This restricts my access s ...

Building an Express API using ES6 script: A Step-by-Step Guide

After creating a no-view REST API using the express generator, I decided to convert everything to ES6 script and compile it with Babel. However, upon entering localhost after the changes, an error message appeared: No default engine was specified and no ...

I desire to perform a specific task when there is a modification in the path using react router framework

Though I am mindful of it. props.history.listen((location, action) => { console.log("when route changes",location); }) However, I need to implement it in a slightly different way. For instance, let's cons ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...

Creating an Ajax request in Angular using ES6 and Babel JS

I have been exploring a framework called angular-webpack-seed, which includes webpack and ES2016. I am trying to make a simple AJAX call using Angular in the traditional way, but for some reason, it is not working. export default class HomeController { ...

Using Jest to mock React components with dot notation

I am facing a challenge with a component that dynamically renders either a main component or a loading component based on the data being loaded: // components/example import Component from 'components/component'; const Example = ({loaded}) =&g ...

Uncover the secrets of retrieving data from a JSON string in PHP, even if you're not aware of

I'm checking a service to see if a person has phone numbers. It returns a json string like this: $json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}'; After using the json_decode() function, I want to extract only the phone nu ...

Error message: Unchecked runtime error - Unable to retrieve data from the specified URL. The extension manifest must include permission to access this particular host. This issue is occurring in manifest

Can someone help me out? I keep on receiving the error messages Unchecked runtime.lastError: Cannot access contents of url. Extension manifest must request permission to access this host. and Unchecked runtime.lastError: Could not establish connection. Rec ...

Is there a way to verify the phone number input field on my registration form along with the country code using geolocation

I'm currently working on a registration form that includes an input field for telephone number. I'd like to implement a feature where, upon filling out the form, the telephone input field automatically displays the country code by default. Would ...

Utilizing browser local storage in web development

Currently, I am in the midst of working on an e-commerce platform, a project that holds significant importance for me as it marks my debut into major projects. For the first time, I am delving into the realm of local storage to manage basket data such as q ...

Ways to verify if a JSON is empty on an Android device

I'm currently working on an Android app that retrieves data from a PHP JSON source. Successfully fetched the JSON data, but encountered a problem when the JSON response is empty, causing the application to stop. Therefore, I am looking for ways to d ...

Removing a Dynamic Element in ReactJS

--CustomFieldSection.js-- import React, { Component } from 'react'; import CustomField from './CustomField.js'; class CustomFieldSection extends Component{ constructor(props){ super(props); this.stat ...