我有以下var:
filter = {
"country": 1,
"Age Group": {},
"Gender": {},
"NEWSEC": {},
"Telco_Segment": {}
};
和功能:
function facetBuilder(key, val)
{
if(key == 'country')
{
filter.country = val;
}
else
{
if(typeof filter[key][val] !== "undefined" )
{
delete filter[key][val]; //I'm assuming you want to remove it
}
else
{
filter[key][val] = true;
}
}
console.log(filter);
}
结果对象最终看起来像这样:
filter = {
"country": 1,
"Age Group": {
4: true,
3: true,
2: true
},
"Gender": {
1: true
},
"NEWSEC": {
3: true,
2: true
},
"Telco_Segment": {}
};
但我真正想要的是这样的:
filter = {
"country": 1,
"Age Group": [4,3,2],
"Gender": [1],
"NEWSEC": [3,2],
"Telco_Segment": []
};
而且我不确定如何处理它。
答案 0 :(得分:4)
而不是
filter[key][val] = true;
怎么样
filter[key].push(val);
和
filter = {
"country": 1,
"Age Group": [],
^^---empty array, instead of {} for object.
答案 1 :(得分:0)
你现在拥有的if(typeof filter[key][val] !== "undefined" )
是好的,因为对象具有恒定时间查找。如果使用数组扫描if(filter[key].indexOf(val) !== -1)
,则时间复杂度会增加到O(n),因为您必须扫描每个元素以查看它是否在数组中。