Creating an arrayof Object from another object

时间:2015-08-07 02:35:50

标签: javascript arrays javascript-objects

I have an object which contains email objects and their properties. I am interested in the mime property () and I can access it using array[index].subtype. I want to create a new array of (MIME) objects that contains only the mime and count.

var mimeType = []
var arr = {"object with emails"}.

    arr.forEach(function(elem, index, array){
     if(mimeType.indexOf(array[index].subtype == -1)){
                            mimeType.push({mime: array[index].subtype,    `count:1});
    }
else{
mimeType[count] = count+1;
}

It print all the mime, with repetition

1 个答案:

答案 0 :(得分:1)

Is this what you want? :

var tmp = {};
var arr = [{ subtype: 'pdf' }, { subtype: 'doc' }, { subtype: 'pdf' }, { subtype: 'pdf' }];

arr.forEach(function(elem, index, array){
    if(tmp[elem.subtype] === undefined){
        tmp[elem.subtype] = 1;
    }
    else {
        tmp[elem.subtype]++;
    }
});

var mimeType = Object.getOwnPropertyNames(tmp).map(function(e) { return { mime: e, count: tmp[e] }});

Result of mimeType =

[{mime:"pdf",count:3},{mime:"doc",count:1}]
相关问题