在javascript中过滤和计算json属性

时间:2017-11-19 04:41:32

标签: javascript json filter

我有一个json对象,我希望在js中分析它们的项目。当我将json记录到控制台时,您可以看到它包含元素items,其中包含相关信息的数组。

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, …}

但是,当我尝试使用filter函数来计算repair_statebroken时的记录数量时,我收到了错误消息:

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

Uncaught TypeError: json.filter is not a function

我做错了什么,在这种情况下如何计算items属性等于repair_state的{​​{1}}的数量?

1 个答案:

答案 0 :(得分:2)

正如我在你的console.log中看到的那样,json是一个对象,其中的items是一个数组,所以你应该对数组 items 应用过滤器。它应该是,

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

<强>样本

&#13;
&#13;
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);
&#13;
&#13;
&#13;