我有一个类似的Javascript对象(真实对象包含超过1,000条记录):
var model = {
"places": [
{
"title": "Centre Island Park",
"id": 1800,
"categories": [
"park"
],
"state": "ON",
"country": "Canada",
"neighborhood": "Downtown"
},
{
"title": "Chagall Bistro",
"id": 2914,
"categories": [
"lounge",
"restaurant"
],
"state": "NY",
"country": "USA",
"neighborhood": "Park Slope"
},
{
"title": "Chai Ko Tapas",
"id": 2365,
"categories": [
"restaurant"
],
"state": "NJ",
"country": "USA",
"neighborhood": "North Jersey"
},
{
"title": "Chatanooga",
"id": 574,
"categories": [
"restaurant"
],
"state": "NY",
"country": "USA",
"neighborhood": "Nassau"
},
{
"title": "Chateau Steakhouse",
"id": 2565,
"categories": [
"restaurant"
],
"state": "NY",
"country": "USA",
"neighborhood": "Queens"
}
]
}
我正在尝试创建一个过滤器,以便按州和类别缩小搜索范围。
我的第一步是创建三个新对象:countries
,states
和categories
。然后,我想为每个对象值填充一个选择框,并将选择传递给我的控制器以用作过滤器。我的第一步是使用vanilla Javascript迭代所有places
并提取所有唯一状态(和国家/地区等)名称,并使用以下代码创建过滤器对象:
var states = [];
model.forEach(function(place) {
var state = place.state;
var stateExists = states.some(function(element) {
return element.name === state;
});
if(!stateExists && state && country) {
states.push({name: state});
}
});
代码运行速度非常慢,所以我切换到underscore.js:
var states = _.chain(model)
.uniq(false, function(value) {return value.state})
.sortBy(function(value) {return value.state})
.filter(function(value) {return value.state})
.map(function(value, key){
return {name: value.state};
})
.value();
但是,代码仍然很慢,我不希望代码中有很多依赖项。 另外,我已经在这个项目中使用了Ember.js,但是我无法弄清楚" Ember"这样做的方式(如果存在)。 有任何建议/技巧可以更有效地完成这项工作吗?
答案 0 :(得分:0)
更有效地完成此任务的任何建议/技巧?
在后端执行过滤和转换。利用REST端点通过AJAX将已转换和过滤的对象返回到控件。正如您目前正在尝试的那样,具有1000多条记录的结果集对于前端处理来说显得过于繁琐。
答案 1 :(得分:0)
经过一番研究,我找到了一个underscore.js解决方案。至少它并没有占用太多代码!
var countries = [];
var states = [];
var categories = [];
model.forEach(function(place) {
if(!_.contains(countries, place.country)) {
countries.push(place.country);
}
if(!_.contains(states, place.state)) {
states.push(place.state);
}
place.categories.forEach(function(category) {
if(!_.contains(categories, category)) {
categories.push(category);
}
});
});