2015-01-10 267 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