iskandarblue
iskandarblue

Reputation: 7526

Filtering and counting json properties in javascript

I have a json object whose items I would like to analyze in js. When I log the json to the console, you can see that it contains the element items which holds an array of the 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 try to use the filter function to count the amount of records where repair_state is broken, I am returned an error:

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

Uncaught TypeError: json.filter is not a function

What am I doing wrong and how would one count the number of items whose repair_state property is equal to broken in this case?

Upvotes: 0

Views: 1415

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222692

As i see from your console.log, json is an object where items is an array inside it, so you should apply filter on the array items. It should be,

  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);

Upvotes: 3

Related Questions