2015-01-21 49 views
-4

分組我有對象的數組路徑的數組如下一個對象的函數:鑑於對象的數組,創建返回具有的由式

var data = [ 
    {name : 'xxxx' , type: 'jpeg' , path: '../'}, 
    {name : 'yyyy' , type: 'gif' , path: '../'}, 
    {name : 'zzzz' , type: 'jpeg' , path: '../'} 
]; 

我想要的結果是在這種格式:

{ 
    jpeg: ['../xxxx.jpeg', '../zzzz.jpeg'], 
    gif:['../yyyy.gif'] 
} 

我嘗試:

function transformData(data) { 
    var result = {}; 
    if (data && data.length > 0) { 
     for (var i = 0; i < data.length; i++) { 
      result[data[i].type] = [data[i].path + data[i].name]; 
     } 
    } 
    console.log(result); 
} 

transformData(data); 
+2

而且?你有什麼問題?你嘗試過嗎? – 2015-01-21 09:37:07

+0

我試過但沒有得到預期的結果。 – Manu 2015-01-21 09:38:10

+0

顯示您的嘗試,以便我們可以幫助您找到您的錯誤。 – 2015-01-21 09:38:34

回答

0

試試這個

var data = [ 
    {name : 'xxxx' , type: 'jpeg' , path: '../'}, 
    {name : 'yyyy' , type: 'gif' , path: '../'}, 
    {name : 'zzzz' , type: 'jpeg' , path: '../'} 
]; 

var res = {}, 
    len = data.length, i; 


for (i = 0; i < len; i++) { 
    if (!res[data[i].type]) { 
    res[data[i].type] = []; 
    } 

    res[data[i].type].push(data[i].path + data[i].name + '.' + data[i].type); 
} 

Example

1

因爲有幾個答案,我給基於reduce的功能之一:

var arr = data.reduce(function(r,m){ 
    (r[m.type]||(r[m.type]=[])).push(m.path+m.name+'.'+m.type); 
    return r; 
},{}); 
+0

無法在IE8或更低版本中使用 – micha 2015-01-21 09:54:07

+0

@micha好的,當然是,但我認爲我們不應該在2015年繼續承擔這個重量。 – 2015-01-21 09:58:27

+0

但是你應該在其他答案中說出來。也許他不想排除ie8 – micha 2015-01-21 10:00:36

-1

可以使用forEach做到這一點:

var data = [ 
    {name : 'xxxx' , type: 'jpeg' , path: '../'}, 
    {name : 'yyyy' , type: 'gif' , path: '../'}, 
    {name : 'zzzz' , type: 'jpeg' , path: '../'} 
]; 

var result = {}; 

data.forEach(function(elem){ 
    result[elem.type] = result[elem.type] || []; 
    result[elem.type].push(elem.path + elem.name + '.' + elem.type); 
}); 

保持記住Array.prototype.forEach()不能用於IE8或更低版本,但mdn頁面有一些polyfills。

+1

夥計們,什麼是downvote?有什麼東西壞了? – Cerbrus 2015-01-21 10:00:00

0

您可以使用Array.prototype.reduce()功能的優雅解決方案。

// Your data 
var data = [ 
    {name : 'xxxx' , type: 'jpeg' , path: '../'}, 
    {name : 'yyyy' , type: 'gif' , path: '../'}, 
    {name : 'zzzz' , type: 'jpeg' , path: '../'} 
]; 

// Solution 
var res = data.reduce(function(prev, current) { 
    ((prev[current.type])||(prev[current.type] = [])).push(current.path + current.name + '.' + current.type); 
    return prev; 
}, {}); 

// console.log(res);