2017-02-03 57 views
-1

可以說我有地圖就像一個列表:組列表

var x = [{"name":"Not1","type":"Email"},{"name":"Not2","type":"Instant"},{"name":"Not3","type":"Email"},{"name":"Not4","type":"Instant"}] 

我所要的輸出是:

var result = {"Email":[{"name":"Not1","type":"Email"}, {"name":"Not3","type":"Email"}],"Instant":[{"name":"Not2","type":"Instant"}, {"name":"Not4","type":"Instant"}]} 

我怎樣才能以最好的方式做到這一點?在此先感謝

+1

使用循環。這實際上是相當微不足道的,沒有什麼魔法可以進一步簡化它。嘗試一下並向我們展示你的嘗試。 – Bergi

回答

0

我認爲這會做你的東西:

 let result = {}; 
     x.forEach((dataObj, index) => { 
      result[dataObj['type']] = result[dataObj['type']] || []; 
      result[dataObj['type']].push(dataObj); 
     }) 
+1

在ES6中,您應該簡單地使用'for(let x dataObj){' – Bergi

+0

@Bergi在使用for循環時這是真的。 :) – psycho

0

或者你可以使用Array.prototype.reduce()功能;

var x = [{"name":"Not1","type":"Email"},{"name":"Not2","type":"Instant"},{"name":"Not3","type":"Email"},{"name":"Not4","type":"Instant"}]; 
 

 
var output = x.reduce(function(accum, item, index) { 
 
    
 
    if(accum[item.type] === undefined) { 
 
     accum[item.type] = []; 
 
    } 
 
    accum[item.type].push({name: item.name, type: item.type}); 
 

 
    return accum; 
 
     
 
}, {}); 
 

 
console.log(JSON.stringify(output));

0

你可以做一個單一的線,用一個空的對象和Array#reduce

var x = [{ name: "Not1", type: "Email" }, { name: "Not2", type: "Instant" }, { name: "Not3", type: "Email" }, { name: "Not4", type: "Instant" }], 
 
    result = x.reduce((r, a) => ((r[a.type] = r[a.type] || []).push(a), r), Object.create(null)); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }