一尘不染

计算对象数组中的特定键值

angularjs

我有以下JSON数组,我想创建对象表单状态键计数

[
  {
    "id": "65:0",    
    "status": "ORANGE"
  },
  {
    "id": "65:0",
    "status": "GREEN"
  },
  {
    "id": "65:0",
    "status": "ORANGE"
  },
  {
    "id": "65:0",
    "status": "YELLOW"
  },
  {
    "id": "65:0",
    "status": "RED"
  },
  {
    "id": "65:0",
    "status": "GREEN"
  },
  {
    "id": "65:0",
    "status": "GREEN"
  },
   {
    "id": "65:0",
    "status": "ORANGE"
  },
  {
    "id": "65:0",
    "status": "YELLOW"
  },
  {
    "id": "65:0",
    "status": "GREEN"
  }
]

要计算状态键值并创建以下对象

{
 'ORANGE' : 3,
 'GREEN' : 4,
 'YELLOW' : 2,
 'RED' : 1,
}

阅读 251

收藏
2020-07-04

共1个答案

一尘不染

使用 Array#reduce 方法

var res = data.reduce(function(obj, v) {
  // increment or set the property
  // `(obj[v.status] || 0)` returns the property value if defined
  // or 0 ( since `undefined` is a falsy value
  obj[v.status] = (obj[v.status] || 0) + 1;
  // return the updated object
  return obj;
  // set the initial value as an object
}, {})



var data = [{

  "id": "65:0",

  "status": "ORANGE"

}, {

  "id": "65:0",

  "status": "GREEN"

}, {

  "id": "65:0",

  "status": "ORANGE"

}, {

  "id": "65:0",

  "status": "YELLOW"

}, {

  "id": "65:0",

  "status": "RED"

}, {

  "id": "65:0",

  "status": "GREEN"

}, {

  "id": "65:0",

  "status": "GREEN"

}, {

  "id": "65:0",

  "status": "ORANGE"

}, {

  "id": "65:0",

  "status": "YELLOW"

}, {

  "id": "65:0",

  "status": "GREEN"

}];



var res = data.reduce(function(obj, v) {

  obj[v.status] = (obj[v.status] || 0) + 1;

  return obj;

}, {})



console.log(res);

虽然可以使用 Array#forEach 具有相同代码的方法。

var res = {};
data.forEach(function(v) {
  res[v.status] = (res[v.status] || 0) + 1;
})



var data = [{

  "id": "65:0",

  "status": "ORANGE"

}, {

  "id": "65:0",

  "status": "GREEN"

}, {

  "id": "65:0",

  "status": "ORANGE"

}, {

  "id": "65:0",

  "status": "YELLOW"

}, {

  "id": "65:0",

  "status": "RED"

}, {

  "id": "65:0",

  "status": "GREEN"

}, {

  "id": "65:0",

  "status": "GREEN"

}, {

  "id": "65:0",

  "status": "ORANGE"

}, {

  "id": "65:0",

  "status": "YELLOW"

}, {

  "id": "65:0",

  "status": "GREEN"

}];



var res = {};

data.forEach(function(v) {

  res[v.status] = (res[v.status] || 0) + 1;

})



console.log(res);
2020-07-04