0

I have a JSON file. I want to find the length of the JSON object where one key-value pair is similar. Like,

https://api.myjson.com/bins/h5mgv

[
  {
    "receive_date": "2013-11-04",
    "responses": "2",
    "name": "west"
  },
  {
    "receive_date": "2013-11-04",
    "responses": "8668",
    "name": "west"
  },
  {
    "receive_date": "2013-11-13",
    "responses": "121",
    "name": "east"
  }
]

In the above example, length is 2 where "name": "west" and length is 1 where "name": "east" . I want to iterate through the JSON and find the identical values for the key name using Javascript. Output should look like,

east : 1
west : 2

By using length() I can find the length of whole JSON but what is recommended way to find the length for identical key values.

Codeleys
  • 45
  • 2
  • 6
  • Sounds like this question: https://stackoverflow.com/questions/19395257/how-to-count-duplicate-value-in-an-array-in-javascript – Iskandar Reza Dec 22 '17 at 20:40

1 Answers1

1

You can use reduce to get a new object listing the count of each name:

const myArray = [
  {
    "receive_date": "2013-11-04",
    "responses": "2",
    "name": "west"
  },
  {
    "receive_date": "2013-11-04",
    "responses": "8668",
    "name": "west"
  },
  {
    "receive_date": "2013-11-13",
    "responses": "121",
    "name": "east"
  }
]

const myCounts = myArray.reduce((counts, item) => {
  if (counts[item.name] === undefined) counts[item.name] = 0;
  counts[item.name]++;
  return counts;
}, {});

console.log(myCounts);

This produces the result:

{
  "west": 2,
  "east": 1
}
CRice
  • 29,968
  • 4
  • 57
  • 70