我正在尝试过滤类似以下内容的数据:
data = {
ABC: "Lorem Ipsum lorem lorem",
DEFG: "Lorem Ipsum lorem lorem",
HI: "Lorem Ipsum lorem lorem",
JK: "Lorem Ipsum lorem lorem"
}
对抗数组如:
myArray = ["HI","LMN","ABC"]
我正在尝试返回myArray
我尝试过以下操作但没有成功:
$scope.filteredResults = $filter("filter")(data, function (val, index) {
for (var i = 0; i < myArray.length; i++) {
if (index === myArray[i]) {
return false
}
}
return true
})
答案 0 :(得分:1)
如果Object的索引是其键,那么您可以使用Array.prototype.indexOf
检查它是否存在于数组中。我假设$scope.filteredResults = $filter("filter")(data, function(val, index) {
return myArray.indexOf(index) === -1;
})
是对象的关键?
var data = {
ABC: "Lorem Ipsum lorem lorem",
DEFG: "Lorem Ipsum lorem lorem",
HI: "Lorem Ipsum lorem lorem",
JK: "Lorem Ipsum lorem lorem"
};
var blackList = ["HI", "LMN", "ABC"];
var filtered = Object.keys(data).filter(function(key) {
return blackList.indexOf(key) === -1;
}).reduce(function(result, key) {
result[key] = data[key];
return result;
}, {});
document.body.innerHTML = JSON.stringify(filtered, null, ' ');
如果要返回已过滤的对象(不包括过滤器列表中存在的任何键),可以按键过滤,然后根据允许的键缩小对象。
这是一个使用黑名单过滤对象的纯JavaScript实现。
body { white-space: pre; font-family: monospace; }
&#13;
<script>
$(document).ready(function()
{
if($('.col-sm-6').children().length > 0) $('.status').text('div has child');
else $('.status').text('no child');
});
</script>
&#13;
答案 1 :(得分:1)
如果您在controller
中执行此操作,为什么不在纯JavaScript中执行此操作?
仅供参考:在纯JavaScript中执行这些简单操作比在Angular Utilities中执行更快。
var data = {
ABC: "Lorem Ipsum lorem lorem",
DEFG: "Lorem Ipsum lorem lorem",
HI: "Lorem Ipsum lorem lorem",
JK: "Lorem Ipsum lorem lorem"
};
var myArray = ["HI", "LMN", "ABC"];
var keys = Object.keys(data);
var result = {};
for (var i = 0; i < keys.length; i++) {
if (myArray.indexOf(keys[i]) == -1) {
result[keys[i]] = data[keys[i]];
}
}
document.body.innerHTML = JSON.stringify(result);
&#13;