我有一个JavaScript对象是通过MSQL查询从PHP创建的。
但是,JavaScript对象并不是我需要的。
JavaScript对象:
var data = [{"name":"Ashley","latitude":"51.46619000","longitude":"-2.58345600","type":"% respondents who go to work (as driver) by car","percentage":"25.3","year":"2013"},{"name":"Ashley","latitude":"51.46619000","longitude":"-2.58345600","type":"% respondents who go to work by walking","percentage":"37.7","year":"2013"},{"name":"Avonmouth","latitude":"51.49275700","longitude":"-2.68259000","type":"% respondents who go to work by train","percentage":"0.0","year":"2013"},{"name":"Avonmouth","latitude":"51.49275700","longitude":"-2.68259000","type":"% respondents who go to work by moped\/motorbike","percentage":"1.2","year":"2013"}...etc];
上面只是一个例子,总共有35个不同的病房"名称"并且每种类型都有一个单独的,即#34;%为每个名字开车上班的人(作为司机)#34;
我需要它为每个名称提供一个对象,并且所有类型和百分比都在子数组中。例如:
var data = [{"name":"Ashley","latitude":"51.46619000","longitude":"-2.58345600”,"types":[{“type”:”% respondents who go to work (as driver) by car”,”percentage”:”25.3”,”year”:”2013”},{"type":"% respondents who go to work by walking","percentage":"37.7","year":"2013”}}...etc]},{"name":"Avonmouth",...etc}];
有没有办法可以在JavaScript中重新构造对象?所以它基本上合并了数据,因此没有重复的名称对象,并且每个名称都将所有类型放入子数组中。
修改
我尝试过stackoverflow的各种解决方案,例如:
var res = {};
$.each(data, function (key, value) {
if (!res[value.name]) {
res[value.name] = value;
} else {
res[value.name].type = [res[value.name].type, value.type].join(',');
}
});
data = $.map(res, function (value) {
return value;
});
console.log(data);
这会删除所有重复的"名称"因此,每个病房名称只有一个,所以只有35个对象(这是对的)。但只保留一种类型和百分比,并删除每个名称的其余部分。
答案 0 :(得分:0)
type
而不是push
..
试试这个..
$.each(data, function (idx, value) {
var type = value.type;
if (!res[value.name]) {
res[value.name] = value;
res[value.name].type = []
}
res[value.name].type.push(type);
});
好吧,它没有处理你需要的其他字段,但是它应该指出你在代码中存在的逻辑错误......你应该能够自己完成任何进一步的工作..