如何从特定值的json获取属性计数

时间:2017-11-07 12:15:36

标签: javascript

var  obj = [  {
        "Name": "USA"
        "Score": 2
    },{
        "Name": "UK"
        "Score": 1
    },{
        "Name": "USA"
        "Score": 2
    },{
        "Name": "UK"
        "Score": 2
    },{
        "Name": "AUS"
        "Score": 1
    },{
        "Name": "NZ"
        "Score": 3
    },{
        "Name": "NZ"
        "Score": 2
    }];

通过这个我使用这个代码来获得分数为“2”的次数。

var count = 0;
for(var key in Obj)
     if(Object.keys(Obj[key]).filter(function(sub){return Obj[key][sub] === "2";}).length) ++count;

现在我的计数值是4.但它只发生在3个国家。有什么方法可以获得这些价值。

我是指得分为“2”的国家/地区的数量。

2 个答案:

答案 0 :(得分:2)

让我们正确地做到这一点。

ES6:

const obj = [{"Name": "USA","Score": 2},{"Name": "UK","Score": 1},{"Name": "USA","Score": 2},{"Name": "UK","Score": 2},{"Name": "AUS","Score": 1},{"Name": "NZ","Score": 3},{"Name": "NZ","Score": 2}];

const result = obj
  .filter(o => o.Score === 2)                // Get the proper score
  .map(o => o.Name)                          // Get the resulting names
  .filter((o,i,a) => i === a.lastIndexOf(o)) // Filter for unique names
  .length;
  
console.log(result);

使用的方法:

ES5,为了向后兼容:

var obj = [{"Name": "USA","Score": 2},{"Name": "UK","Score": 1},{"Name": "USA","Score": 2},{"Name": "UK","Score": 2},{"Name": "AUS","Score": 1},{"Name": "NZ","Score": 3},{"Name": "NZ","Score": 2}];

var result = obj
  .filter(function(o){
    return o.Score === 2;
  })
  .map(function(o){
    return o.Name
  })
  .filter(function(o,i,a){
    return i === a.lastIndexOf(o);
  })
  .length;
  
console.log(result);

答案 1 :(得分:-2)

使用Array.prototype.filter()获取匹配元素并使用Array.length

<强>样本

var myobj = [{
    "Name": "USA",
    "Score": 2
},{
    "Name": "UK",
    "Score": 1
},{
    "Name": "USA",
    "Score": 2
},{
    "Name": "UK",
    "Score": 2
},{
    "Name": "AUS",
    "Score": 1
},{
    "Name": "NZ",
    "Score": 3
},{
    "Name": "NZ",
    "Score": 2
}];

var result = myobj.filter(t => t.Score === 2);
console.log(result.length);

修改

 var myobj = [{
        "Name": "USA",
        "Score": 2
    },{
        "Name": "UK",
        "Score": 1
    },{
        "Name": "USA",
        "Score": 2
    },{
        "Name": "UK",
        "Score": 2
    },{
        "Name": "AUS",
        "Score": 1
    },{
        "Name": "NZ",
        "Score": 3
    },{
        "Name": "NZ",
        "Score": 2
    }];

var result = _.uniq(_.map(myobj, 'Score')).length
  
 console.log(result);
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>