【问题标题】:JSON manipulation - count keys with same value, create new object with count as valueJSON 操作 - 计算具有相同值的键,创建以计数为值的新对象
【发布时间】:2020-07-04 04:37:03
【问题描述】:

我想统计具有相同日期的JSON节点,并创建一个以日期为键、计数为值的新对象。

那么,无论是使用 jQuery 还是 vanilla JS,我将如何转换:

[
  {
    "date": "January 1"
  },
  {
    "date": "January 1"
  },
  {
    "date": "January 1"
  },
  {
    "date": "January 1"
  },
  {
    "date": "February 14"
  },
  {
    "date": "February 14"
  },
  {
    "date": "July 8"
  },
  {
    "date": "July 8"
  },
  {
    "date": "July 8"
  },
  {
    "date": "December 11"
  }
]

进入这个:

[
  {
    "January 1": 4 // Number or String "4", doesn't matter
  },
  {
    "February 14": 2
  },
  {
    "July 8": 3
  },
  {
    "December 11": 1
  }
]

【问题讨论】:

  • 这是一个相当简单的任务,它使用了几种不同的循环/数组方法之一。你在实现目标时遇到了什么问题,你做了什么尝试?

标签: javascript jquery json transform


【解决方案1】:

试试这样的。

const data = [
  {
    "date": "January 1"
  },
  {
    "date": "January 1"
  },
  {
    "date": "January 1"
  },
  {
    "date": "January 1"
  },
  {
    "date": "February 14"
  },
  {
    "date": "February 14"
  },
  {
    "date": "July 8"
  },
  {
    "date": "July 8"
  },
  {
    "date": "July 8"
  },
  {
    "date": "December 11"
  }
]

let counter = {}

data.forEach(function(obj) {
    var key = obj.date
    counter[key] = (counter[key] || 0) + 1
})

console.log(counter)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-03
    • 1970-01-01
    • 2011-08-19
    • 2021-07-25
    • 2015-06-30
    • 2020-04-05
    • 2018-12-23
    • 1970-01-01
    相关资源
    最近更新 更多