0

我一直在尝试实现过滤 JS 映射对象(由 id 索引的数组),而不是 angularJS 中通常的 js 数组。

为了说明,下面是AngularJS 文档中提供的过滤示例的轻微修改。

http://plnkr.co/edit/bNzePyuAAmP6Nl6hj5bI?p=preview

我已将输入数组(朋友)转换为 JSON 对象,每个初始数组元素都映射为单独的键控元素。这种修改可以理解如下:

初始(如 AngularJS 文档中所示):

friends = [{name:'John', phone:'555-1276'},
           {name:'Mary', phone:'800-BIG-MARY'},
           {name:'Mike', phone:'555-4321'},
           {name:'Adam', phone:'555-5678'},
           {name:'Julie', phone:'555-8765'}]

修改的:

friends = {1:{name:'John', phone:'555-1276'},
           2:{name:'Mary', phone:'800-BIG-MARY'},
           3:{name:'Mike', phone:'555-4321'},
           4:{name:'Adam', phone:'555-5678'},
           5:{name:'Julie', phone:'555-8765'}}

有人可以提供一种方法来过滤这样的输入作为 ng-repeat 指令过滤器表达式的一部分。我知道“朋友”不再是一个数组而是一个对象,但是由于 ng-repeat 指令正在处理这个对象,也许还有一种过滤它的方法?

谢谢。

4

1 回答 1

1

jsFiddle Demo- 修改 json 结构

jsFiddle Demo- 原始的json结构

对于您的小样本,此示例可能非常强大,但随着您的样本变得更加复杂,这仍将处理过滤。

使用递归函数查找对象。最初由我在这里发布:https ://stackoverflow.com/a/11657379/1026459

function ContainsKeyValue( obj, key, value ){
 if( obj[key] === value ) return true;
 for( all in obj )
 {
    if( obj[all] != null && obj[all][key] === value ){
        return true;
    }
    if( typeof obj[all] == "object" && obj[all]!= null ){
        var found = ContainsKeyValue( obj[all], key, value );
        if( found == true ) return true;
    }
 }
 return false;
}

您可以在修改或不修改您拥有的原始结构的情况下利用此功能。

var friends = {1:{name:'John', phone:'555-1276'},
       2:{name:'Mary', phone:'800-BIG-MARY'},
       3:{name:'Mike', phone:'555-4321'},
       4:{name:'Adam', phone:'555-5678'},
       5:{name:'Julie', phone:'555-8765'}};

var filteredFriends = [];
for( var friend in friends )
{
 if( ContainsKeyValue( friends[friend], "name", "John" ) === true )
 {
    filteredFriends.push( friends[friend] );//or directly use the john object here
 }
}
console.log(filteredFriends);//this will contain an array of friends named John.
于 2013-06-18T20:31:20.313 回答