Javascript计算有多少车库有carmake1 [英] Javascript Count how many garages have carmake1

查看:85
本文介绍了Javascript计算有多少车库有carmake1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示为车库的数据。
我需要例如计算有carmake1的车库数量

I have an oject of data represented as garages. I need to for example count the number of garages that have carmake1

我试过这个:

count = obj.garages.filter(function(item) { return item === "carmake1" }).length;

但这会返回0,我们知道数据中有实际的carmake1。

but this returns 0 and we know there are actual carmake1's in the data.

以下是数据:

obj = {
  "garages": [{
      "id": "1",
      "carId": "1",
      "tags": {
        "483": "carmake1",
        "485": "carmake3"
      }
    },
    {
      "id": "2",
      "carId": "1",
      "tags": {
        "483": "carmake1",
        "485": "carmake3"
      }
    },
    {
      "id": "3",
      "carId": "2",
      "tags": {
        "484": "carmake2",
        "485": "carmake3"
      }
    },
    {
      "id": "4",
      "carId": "2",
      "tags": {
        "483": "carmake1",
        "485": "carmake3"
      }
    },
    {
      "id": "5",
      "carId": "3",
      "tags": {
        "484": "carmake2",
        "485": "carmake3"
      }
    },
  ]
};

我怎样才能得到它?

推荐答案

您可以通过检查财产来计算。

You could count it with the check of the property.

var obj = obj = { "garages": [{ "id": "1", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "2", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "3", "carId": "2", "tags": { "484": "carmake2", "485": "carmake3" } }, { "id": "4", "carId": "2", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "5", "carId": "3", "tags": { "484": "carmake2", "485": "carmake3" } }, ] },
    count = obj.garages.filter(function(item) {
        return item.tags[483] === "carmake1"
    }).length;

console.log(count);

或检查所有属性标记

var obj = obj = { "garages": [{ "id": "1", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "2", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "3", "carId": "2", "tags": { "484": "carmake2", "485": "carmake3" } }, { "id": "4", "carId": "2", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "5", "carId": "3", "tags": { "484": "carmake2", "485": "carmake3" } }, ] },
    count = obj.garages.filter(function (item) {
        return Object.keys(item.tags).some(function (k) {
            return item.tags[k] === "carmake1"
        });
    }).length;

console.log(count);

这篇关于Javascript计算有多少车库有carmake1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆