简体   繁体   中英

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?

 myObject = [{ "object": [{ "id": "8062", "name": "name 1", "tags": ['tag1', 'tag2'], "desc": "desc 1" }, { "id": "8061", "name": "name 2", "tags": ['tag2', 'tag3'], "desc": "desc 2" }, { "id": "8060", "name": "name 3", "tags": ['tag2', 'tag3'], "desc": "desc 3" }] }]; var map = {}; myObject[0].object.forEach(function(object) { object.tags.forEach(function(tag) { if(map[tag] === undefined){ map[tag] = 1; }else{ map[tag] = map[tag] + 1; } }); }); console.log(map); 

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) 

Simply iterate through the array using for-of loop, get each length of tags property and store each desired value to different variables.

var i = 1;
for (obj of myObject[0].object) {
    window["tag" + i + "_count"] = obj.tags.length; // e.g. tag1_count = 2, tag2_count = 3, etc...
    i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM