Marcos Belunti Marcos Belunti - 1 month ago 5
JSON Question

Javascript count values on array

I have some data and one of the fields is called tags and in will sometimes contain an array of values.

What I need to do is to count those values and get them into separate variables.

Here is the data:

myObject = [

{
"object": [
{
"id": "8062",
"name": "name 1"
"tags": ['tag1','tag2'],
"desc": "desc 1",
},
{
"id": "8061",
"name": "name 2"
"tags": ['tag 2', 'tag 3'],
"desc": "desc 2"

},
{
"id": "8060",
"name": "name 3"
"tags": ['tag 2', 'tag 3'],
"desc": "desc 3"

}
]
}

];


And this is what I need to end up with:

tag1_count = 1;
tag2_count = 3;
tag3_count = 2;


How can I do this?

Answer

You can use reduce() like this and return object.

var myObject = [{
  "object": [{
    "id": "8062",
    "name": "name 1",
    "tags": ['tag1', 'tag2'],
    "desc": "desc 1",
  }, {
    "id": "8061",
    "name": "name 2",
    "tags": ['tag 2', 'tag 3'],
    "desc": "desc 2"
  }, {
    "id": "8060",
    "name": "name 3",
    "tags": ['tag 2', 'tag 3'],
    "desc": "desc 3"

  }]
}];

var result = myObject[0].object.reduce(function(r, e) {
  e.tags.forEach(function(t) {
    var key = t.replace(/ /g, '') + '_count'
    r[key] = (r[key] || 0) + 1;
  })
  return r;
}, {})

console.log(result)

Comments