【问题标题】:How to know quantity of objects that has specific property in common?如何知道具有特定共同属性的对象的数量?
【发布时间】:2018-10-23 15:45:42
【问题描述】:

拥有一个对象数组,我如何确定具有特定共同属性的对象的数量?

例如:

[{"color": "red"},{"color": "red", "size": "big"},{"color": "red", "size": "big"}];

如何获取具有“大小”属性的对象的数量?

【问题讨论】:

  • 你可以进行过滤,然后得到结果的长度。

标签: javascript jquery arrays object


【解决方案1】:

为此,您可以使用filter()hasOwnProperty() 来检索数组中具有size 属性的对象。然后你可以得到length 知道有多少。

var arr = [{
  "color": "red"
}, {
  "color": "red",
  "size": "big"
}, {
  "color": "red",
  "size": "big"
}];

var result = arr.filter(x => x.hasOwnProperty('size'));
console.log(result.length);

【讨论】:

    【解决方案2】:

    你可以.reduce数组来计算对象的数量:

     array.reduce((count, el) => count + ("size" in el), 0)
    

    【讨论】:

      【解决方案3】:

      您可以过滤数组以仅返回键为 size 的数组,然后使用 .length 显示有多少个

      const myArray = [{
        "color": "red"
      }, {
        "color": "red",
        "size": "big"
      }, {
        "color": "red",
        "size": "big"
      }];
      
      const howManySize = myArray.filter(a => a.size).length;
      
      console.log(howManySize);

      【讨论】:

      • 注意:"size": """size": 0 将失败
      • 是的,同意。我是根据 OP 来回答的,不过这一点说得很好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 2016-12-17
      • 1970-01-01
      • 2013-12-22
      • 2014-11-27
      • 2016-11-28
      相关资源
      最近更新 更多