如果我的问题不明确,我提前道歉,我刚开始学习Javascript,这是我的第一篇文章。我正在尝试重新格式化数据集:
console.log(dataset)
显示以下内容(我在这里显示几条记录):
[{"name":"HPH","income":["1976","2434"]},
{"name":"HPH","income":["1977","1658"]},
{"name":"HPH","income":["1978","1712"]},
{"name":"SWO","income":["1976","9913"]},
{"name":"SWO","income":["1977","8852"]},
{"name":"SWO","income":["1978","7152"]}]
我想得到以下内容:
[{"name":"HPH","income":[["1976","2434"],["1977","1658"],["1978","1712"]]},
{"name":"SWO","income":[["1976","9913"],["1977","8852"],["1978","7152"]]}]
任何帮助将不胜感激。
谢
答案 0 :(得分:0)
尝试这样的事情:
var data = [{"name":"HPH","income":["1976","2434"]},
{"name":"HPH","income":["1977","1658"]},
{"name":"HPH","income":["1978","1712"]},
{"name":"SWO","income":["1976","9913"]},
{"name":"SWO","income":["1977","8852"]},
{"name":"SWO","income":["1978","7152"]}];
var final = [],
found = false,
i, j;
for (i in data) {
for(j in final) {
if (final[j].name == data[i].name) {
found = true;
final[j].income.push(data[i].income);
break;
}
}
if (found) {
found = false;
continue;
}
var obj = {name: data[i].name, income: [data[i].income]};
final.push(obj);
}
console.log(final);
答案 1 :(得分:0)
var a = [{"name":"HPH","income":["1976","2434"]},
{"name":"HPH","income":["1977","1658"]},
{"name":"HPH","income":["1978","1712"]},
{"name":"SWO","income":["1976","9913"]},
{"name":"SWO","income":["1977","8852"]},
{"name":"SWO","income":["1978","7152"]}],
b = {},
c = [];
for(var i = 0; i < a.length; i++) {
if(!b[a[i].name])b[a[i].name] = [];
for(var j = 0; j < a[i].income.length){
b[a[i].name].push(a[i].income[j]);
}
}
// Here you have an object like
// b = {HPH : ["1976","2434", "1978","1712"], SWO : ["1977","8852", "1977","8852","1978","7152"};
for(var k in b){
c.push({name : k, income : b[k]}
}
我邀请您阅读:Eloquent JS这是一个非常有帮助的阅读,如果您有动力(MDN(Arrays))成为专业人士!
答案 2 :(得分:0)
另请尝试使用filter
和reduce
:
var dataset = [{"name":"HPH","income":["1976","2434"]},{"name":"HPH","income":["1977","1658"]},{"name":"HPH","income":["1978","1712"]},{"name":"SWO","income":["1976","9913"]},{"name":"SWO","income":["1977","8852"]},{"name":"SWO","income":["1978","7152"]}];
var result = dataset.reduce(function(data, item){
var existitem = data.filter(function(i){
return i.name === item.name
})[0] || {name: item.name, income: []};
!existitem.income.length && data.push(existitem);
existitem.income.push(item.income);
return data
}, [])
document.write(JSON.stringify(result))