JavaScript:将对象中的数据分组 [英] Javascript: group data in objects
问题描述
我正在尝试找出用Javascript组织此数据的最佳方法,因此,如果这个问题比平时更广泛,我深表歉意。
I'm trying to figure out the best way to organize this data in Javascript, so I apologize if this question is broader than usual.
我有数据:
State, Zip
"CA", "945"
"CA", "934"
"MA", "934"
"MA", "021"
"MA", "021"
etc.
我正在尝试创建某种Javascript数组,可以引用该Javascript数组以获取所有 Zip
某个州
I am trying to create some sort of Javascript Array that I can reference to get all the Zip
in a certain State
此引用可能类似于:
State: "CA", Zip:["945", "934"]
State: "MA", Zip:["934", "021", "021"]
这有意义吗?
我想这样做是因为在极少数情况下3位数字 Zip
将存在于两个 State
s中(如上例所示)。
I want to do it this way because on rare occasion a 3-digit Zip
would exist in two State
s (as in the example above).
我正在使用下面的代码,但是它不起作用。
I was playing with the below code, but it does not work.
var stateArray = [],
var zipMapper = [];
for (var i = 0; i < data.length; i++){
if (_.contains(stateArray,data[i].state) == false) {
stateArray.push(data[i].state)
zipMapper.push({state: data[i].state, zips: []})
zipMapper[data[i].state].zips.push(data[zip])
} else {
zipMapper[data[i].state].zips.push(data[zip])
}
}
推荐答案
我建议将数据结构更改为
I suggest to change the data structure to version with fast access to the state and their Zips.
{
"CA": [
"945",
"934"
],
"MA": [
"934",
"021",
"021"
]
}
要从 CA $ c获取拉链$ c>,只需采用
grouped.CA
或 grouped ['CA']
。
您建议解决方案始终需要进行一次交互,直到找到状态的数据。
The solution, you suggested, need always an interation until the data for a state is found. It makes access slow.
var data = [{ State: "CA", Zip: "945" }, { State: "CA", Zip: "934" }, { State: "MA", Zip: "934" }, { State: "MA", Zip: "021" }, { State: "MA", Zip: "021" }],
grouped = function (array) {
var r = {};
array.forEach(function (a) {
r[a.State] = r[a.State] || [];
r[a.State].push(a.Zip);
});
return r;
}(data);
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
这篇关于JavaScript:将对象中的数据分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!