【问题标题】:Count object property inside array using lodash or vanilla javascript使用 lodash 或 vanilla javascript 计算数组内的对象属性
【发布时间】:2017-06-30 11:16:02
【问题描述】:

我有这个带有嵌套数组/对象的对象:

{
"USA": [
    {
        "location": "New York",
        "municipality": "Manhattan",
    },
    {
        "location": "Texas",
        "municipality": "Austin",
    }
  ],
"CANADA": [
    {
        "location": "Ontario",
        "municipality": "no municipality",
    }
  ]
}

我想使用 lodash 或纯 javascript 来计算 USACANADA 中有多少 location。这怎么可能?

想要的结果:

USA: 2
CANADA: 1

【问题讨论】:

    标签: javascript arrays lodash


    【解决方案1】:

    只需使用数组长度:

    var USA = myObj.USA.length;
    var Canada = myObj.CANADA.length;
    

    或者,对于更大的数据集:

    var result = {};
    Object.keys(myObj)
        .forEach(function(key,index) {
            result[key] = myObj[key].length;
        });
    

    【讨论】:

    • 我想迭代,数组有 ~400 个对象
    • @StathisNtonas:为此添加了一个示例。
    【解决方案2】:

    使用 lodash 你可以使用mapValues:

    let result = _.mapValues(data, 'length');
    

    【讨论】:

      【解决方案3】:

      使用Array.prototype.reduce()函数的解决方案:

      var obj = {
              "USA": [ { "location": "New York", "municipality": "Manhattan" }, { "location": "Texas", "municipality": "Austin" } ], "CANADA": [ { "location": "Ontario", "municipality": "no municipality" }] 
          },
      
          result = Object.keys(obj).reduce(function(r,k){
              r[k] = obj[k].length;
          	return r;
          }, {});
      
      console.log(result)

      【讨论】:

        猜你喜欢
        • 2021-01-19
        • 1970-01-01
        • 2016-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-31
        • 1970-01-01
        • 2014-02-14
        相关资源
        最近更新 更多