2017-09-12 70 views
-1

起初,我有此數組:分組對象由多個鍵

[{ 
    "vendorid": 1, 
    "vendorname": "Vendor1", 
    "maxfilelimit": 2, 
    "uploadfilename": "Voice1.xlsx" 
}, 
{ 
    "vendorid": 1, 
    "vendorname": "Vendor1", 
    "maxfilelimit": 2, 
    "uploadfilename": "Ven1_Voice.xlsx" 
}, 
{ 
    "vendorid": 2, 
    "vendorname": "Vendor2", 
    "maxfilelimit": 2, 
    "uploadfilename": "Voice2.xlsx" 
}, 
{ 
    "vendorid": 2, 
    "vendorname": "Vendor2", 
    "maxfilelimit": 2, 
    "uploadfilename": "Ven2_Voice.xlsx" 
}] 

我想,沒有重複的記錄數組中的文件名。所以,我希望類似的輸出如下:

[{ 
    "vendorid": 1, 
    "vendorname": "Vendor1", 
    "maxfilelimit": 2, 
    "uploadfilename": ["Voice1.xlsx", "Ven1_Voice.xlsx"] 
}, { 
    "vendorid": 2, 
    "vendorname": "Vendor2", 
    "maxfilelimit": 2, 
    "uploadfilename": ["Voice2.xlsx", "Ven2_Voice.xlsx"] 
}] 

我發現像d3.js,alaSQL,但沒有得到輸出一些解決方案如預期

+0

'''array.reduce'''是你的朋友。 – Wainage

+0

謝謝!你能解釋我如何在我的場景中使用它? –

+0

取決於。你的數據有哪些變化,以及保持不變?當它發生變化時,重要的是什麼。我可以看到你需要一個文件名數組......還有什麼? – Wainage

回答

1

您可以使用array#reduce,並在它裏面,你可以存儲你的結果一個對象,然後使用Object.values()提取值。

var data = [{"vendorid": 1,"vendorname": "Vendor1","maxfilelimit": 2,"uploadfilename": "Voice1.xlsx"},{"vendorid": 1,"vendorname": "Vendor1","maxfilelimit": 2,"uploadfilename": "Ven1_Voice.xlsx"},{"vendorid": 2,"vendorname": "Vendor2","maxfilelimit": 2,"uploadfilename": "Voice2.xlsx"},{"vendorid": 2,"vendorname": "Vendor2","maxfilelimit": 2,"uploadfilename": "Ven2_Voice.xlsx"}]; 
 

 
var result = data.reduce((hash, obj) => { 
 
    let key = obj.vendorid+'|' +obj.vendorname+'|' +obj.maxfilelimit; 
 
    if(hash[key]) 
 
     hash[key].uploadfilename.push(obj.uploadfilename); 
 
    else { 
 
     hash[key] = obj; 
 
     hash[key].uploadfilename = [obj.uploadfilename]; 
 
    } 
 
    return hash; 
 
},{}); 
 
console.log(Object.values(result));
.as-console-wrapper { max-height: 100% !important; top: 0; }

3
var data = [{ 
    "vendorid": 1, 
    "vendorname": "Vendor1", 
    "maxfilelimit": 2, 
    "uploadfilename": "Voice1.xlsx" 
}, 
{ 
    "vendorid": 1, 
    "vendorname": "Vendor1", 
    "maxfilelimit": 2, 
    "uploadfilename": "Ven1_Voice.xlsx" 
}, 
{ 
    "vendorid": 2, 
    "vendorname": "Vendor2", 
    "maxfilelimit": 2, 
    "uploadfilename": "Voice2.xlsx" 
}, 
{ 
    "vendorid": 2, 
    "vendorname": "Vendor2", 
    "maxfilelimit": 2, 
    "uploadfilename": "Ven2_Voice.xlsx" 
}]; 
; 
// create lookup table 
let lookup = data.reduce((p, v) => { 
    // seen me yet? 
    if (p[v.vendorid]) { 
    p[v.vendorid].uploadfilename.push(v.uploadfilename); 
    } else { 
    // nope ... first time 
    p[v.vendorid] = v; 
    // create array of filenames 
    p[v.vendorid].uploadfilename = [v.uploadfilename]; 
    } 
    return p; 
}, {}); 

// convert back to array 
Object.keys(lookup).map(key => lookup[key]);