我有以下JSON对象:
var data =JSON.parse('[{"Title":"Test 1","State":"Colorado"},
{"Title":"Test 1","State":"Arizona"},
{"Title":"Test 2","State":"Utah"},
{"Title":"Test 2","State":"Arizona"},
{"Title":"Test 3","State":"Arizona"}]');
如何解析此data
对象,以便获得以下输出:
resultData = [{"Title":"Test 1", State: ["Colorado", "Arizona"]},
{"Title":"Test 2", State: ["Utah", "Arizona"]},
{"Title":"Test 3", State: ["Arizona"]}]
到目前为止,我尝试了以下内容:
var resultData = {},
groupBy = "Title";
for (var i = 0; i < data.length; i++) {
if (!resultData[data[i][groupBy]])
resultData[data[groupBy]] = [];
resultData[data[i][groupBy]].push(data[i]);
};
但它没有帮助并返回一些奇怪的物体,如下所示:
resultData = [{Test 1: [{State: "Colorado"}, {State: "Arizona"}]},
{Test 2: [{State: "Utah"}, {State: "Arizona"}]},
{Test 3: [{State: "Arizona"}]}]
有人可以帮我实现同样的目标。
答案 0 :(得分:4)
你想要实现的目标是减少的完美案例:
var data =JSON.parse('[{"Title":"Test 1","State":"Colorado"},
{"Title":"Test 1","State":"Arizona"},
{"Title":"Test 2","State":"Utah"},
{"Title":"Test 2","State":"Arizona"},
{"Title":"Test 3","State":"Arizona"}]');
var titles = data.reduce(function(acc, item){
var title = item.Title;
var state = item.State;
if (!Object.prototype.hasOwnProperty.call(acc, title)){
acc[title] = [];
}
acc[title].push(state);
return acc;
}, {});
var resultData = Object.keys(titles).map(function(title){
return {
Title: title,
State: titles[title]
}
});
var data = JSON.parse('[{"Title":"Test 1","State":"Colorado"}, {"Title":"Test 1","State":"Arizona"},{"Title":"Test 2","State":"Utah"},{"Title":"Test 2","State":"Arizona"},{"Title":"Test 3","State":"Arizona"}]');
var titles = data.reduce(function(acc, item) {
var title = item.Title;
var state = item.State;
if (!Object.prototype.hasOwnProperty.call(acc, title)) {
acc[title] = [];
}
acc[title].push(state);
return acc;
}, {});
var resultData = Object.keys(titles).map(function(title) {
return {
Title: title,
State: titles[title]
}
});
console.log(resultData)
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您可以使用单循环方法,在相同组的哈希表上使用闭包。
var data = [{ Title: "Test 1", State: "Colorado" }, { Title: "Test 1", State: "Arizona" }, { Title: "Test 2", State: "Utah" }, { Title: "Test 2", State: "Arizona" }, { Title: "Test 3", State: "Arizona" }],
key = 'Title',
grouped = data.reduce(function (group) {
return function (r, o) {
if (!group[o[key]]) {
group[o[key]] = [];
r.push({ Title: o.Title, State: group[o[key]] });
}
group[o[key]].push(o.State);
return r;
};
}(Object.create(null)), []);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }