2015-01-10 29 views
0

进出口新的强调和努力实现以下:我有一个查找收集和结果收集:如何将元素添加到集合

$scope.Countries:[{Country:UK,City:London,Areacode:567}, 
{Country:USA,City:Texas,Areacode:987}, 
{Country:CHINA,City:XXX,Areacode:XXX}] 

$scope.People= [{Fname:'John',Country:'USA'},{Fname:'Bob',Country:'UK'},]; 

我希望有一个单一的集合,这将增加该国领域根据他们的映射国家如下人收藏:

$scope.Result=[{Fname:'John',Country:'USA',City:Texas,Areacode:987} 
,{Fname:'Bob',Country:'UK',City:London,Areacode:567}]; 

有人可以扔在如何实现这一目标使用下划线的一些情况。

回答

1

Map整个人收藏和extend每个人提供相应的国家:

var countries = [ 
     {Country:'UK', City:'London', Areacode:567}, 
     {Country:'USA', City:'Texas', Areacode:987} 
    ]; 

    var people = [ 
     {Fname:'John', Country:'USA'}, 
     {Fname:'Bob', Country:'UK'}, 
     {Fname:'Jane', Country:'UK'}, 
     {Fname:'Dai', Country:'WALES'} 
    ]; 

    var result = _.map(people, function(person){ 
     var country = _.findWhere(countries, { Country: person.Country }); 
     return _.extend(person, country); 
    }); 
+0

非常感谢,我使用下面的'code'实现了同样的效果var some_map = _ 。地图( $ scope.People,function(item)var child = _。where($ scope.Countries,{Country:item.Country}); item.City = child [0] .City; item.AreaCode = child [0] .Areacode; 退货项目; });但是我们的代码更加简单和整洁。 – Andrea

0

使用过滤器:

$scope.result = _.filter($scope.people, function(person) { 
    person.country === 'USA'; // or some other value 
}); 
+0

感谢您的答复,过滤器会导致从收集,但进出口的匹配行没有寻找that.I想知道如何结合这两个集合以一种简单的方式,而不是使用for循环和创建一个新的集合... – Andrea