2015-07-13 79 views
0

我已经通过类似的问题进行了搜索,并试图自行解决这个问题,但是我的编程技巧很薄弱。转换JavaScript Array,创建表格视图

我有这样一个数组:

[{"city": "Amsterdam", "year": "2013", "amount": "450"}, 
{"city": "Rotterdam", "year": "2013", "amount": "620"}, 
{"city": "Geneva", "year": "2014", "amount": "530"}, 
{"city": "Rotterdam", "year": "2015", "amount": "350"}] 

,我想用“城市”和“年”获得“量”来改变它。例如。鹿特丹:[620,N/A,350]。 “不适用”,因为2014年的价值缺失。 我正在检查地图功能等,但我的技能很弱。最后我想创建一个有年份(水平)和城市(垂直)的表格视图。 请指教。谢谢

+1

向我们展示你尝试了一些代码。 – doldt

+0

尝试看看[减少](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)函数 – Grundy

+0

@mplungjan你有猎鹰的眼睛,但我已编辑帖子已经并纠正了这一点。编辑尚未批准。 – cezar

回答

1

我不认为这是编程技能,但算法技能。下面是一个代码做你想要什么:

var amounts = [{"city": "Amsterdam", "year": "2013", "amount": "450"},{"city": "Rotterdam", "year": "2013", "amount": "620"},{"city": "Geneva", "year": "2014", "amount": "530"},{"city": "Rotterdam", "year": "2015", "amount": "350"}], 
 
    formattedAmounts = {} 
 
; 
 
       
 
for (var i = 0; i < amounts.length; i++) { 
 
    var amount = amounts[i]; 
 
    
 
    if (undefined === formattedAmounts[amount.city]) { 
 
     formattedAmounts[amount.city] = {}; 
 
    } 
 

 
    formattedAmounts[amount.city][amount.year] = amount.amount; 
 
} 
 

 
console.log(JSON.stringify(formattedAmounts)); 
 
alert(JSON.stringify(formattedAmounts)); 
 

 
function getCityAmount(city) { 
 
    var years = [2013, 2014, 2015], 
 
     cityAmounts = [] 
 
    ; 
 

 
    for (var i = 0; i < years.length; i++) { 
 
     cityAmounts.push(
 
      formattedAmounts[city] && formattedAmounts[city][years[i]] 
 
       ? formattedAmounts[city][years[i]] 
 
       : 'N/A' 
 
     ); 
 
    } 
 

 
    return cityAmounts; 
 
} 
 

 
console.log(JSON.stringify(getCityAmount('Amsterdam'))); 
 
alert(JSON.stringify(getCityAmount('Amsterdam'))); 
 

 
function getCitiesAmounts() { 
 
    var citiesAmounts = []; 
 

 
    for (var i = 0; i < amounts.length; i++) { 
 
     citiesAmounts.push(getCityAmount(amounts[i].city)); 
 
    } 
 

 
    return citiesAmounts; 
 
} 
 

 
console.log(JSON.stringify(getCitiesAmounts())); 
 
alert(JSON.stringify(getCitiesAmounts()));

+0

我更新了片段以获取您要求的格式。 – Gnucki

+0

非常感谢。它工作正常,但我怎么得到“不适用”,当缺少组合?我希望获得与月数相同数量的金额,即使月份的值缺失。 – Qben

+0

非常感谢 – Qben