我搜索过类似的问题并尝试自己解决这个问题,但我的编程能力很弱。
我有一个像这样的数组:
[{"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]。 “N/A”,因为缺少 2014 年的值。 我正在检查 map 功能等,但我的技能很弱。 最后,我想创建一个包含年份(水平)和城市(垂直)的表格 View 。 请指教。谢谢
最佳答案
我认为这不是编程技巧而是算法技巧。这是执行您想要的操作的代码:
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()));
关于javascript - 转换 JavaScript 数组,创建表格 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31377665/