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.

1

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.