2016-05-14 45 views
0

我正在嘗試在我正在製作的angularjs應用程序中執行某些操作。我有很多電影,包括導演,製片人,電影組等等,我想創作一個只有導演的新陣列。Javascript/AngularJs - 如何用另一個數組中的對象填充數組?

我不知道如何用特定對象填充新數組形成另一個數組。 這裏是我的意思是一個快速簡單的例子:

this.products = [ 
    {name: "apple", category: "fruit"}, 
    {name: "iPhone", category: "tech"}, 
    {name: "banana", category: "fruit"} 
]; 

this.fruits = []; 

for(i = 0; i < products.length; i++) { 
    if (products.category[i] == "fruit") { 
    /*code to add object to fruits array*/ 
} 
} 

請幫幫忙!謝謝!

+0

[Array.prototype.push](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/推) – Itay

+0

根據預期的結果可以使用衆多的javascript數組方法 – charlietfl

+0

[Append to array]的可能重複(http://stackoverflow.com/questions/351409/appending-to-array) – rohithpr

回答

0

使用filter API:

this.fruits = this.products.filter(function(product) { 
        return product.category == 'fruits'; 
       }); 
1

試試這個:

for(i = 0; i < products.length; i++) { 
    if (products[i].category == "fruit") { 
     fruits.push(products[i].name) 
    } 
} 
1

與此代碼試試這個可以做有助於您

this.products = [ 
    {name: "apple", category: "fruit"}, 
    {name: "iPhone", category: "tech"}, 
    {name: "banana", category: "fruit"} 
]; 

this.fruits = []; 

for(i = 0; i < products.length; i++) { 
    if (products[i].category === "fruit") { 
     /*code to add object to fruits array*/ 

     fruits.push(products[i].name); 
    } 
} 

console.log(fruits); 
0

你可以做到這一點,如下所示:

this.fruits = this.products.filter(p => p.category == "fruit").map(p => p.name); 

.filter()方法只獲取具有正確類別的對象。然後.map()檢查此結果,並僅用名稱屬性值替換對象,以便最終結果爲["apple", "banana"]

如果你想要整個對象,那麼當然你會忽略.map()部分。

演示:

new (function() { 
 
    this.products = [ 
 
     {name: "apple", category: "fruit"}, 
 
     {name: "iPhone", category: "tech"}, 
 
     {name: "banana", category: "fruit"} 
 
    ]; 
 

 
    this.fruits = this.products.filter(p => p.category == "fruit").map(p => p.name); 
 

 
    document.write(this.fruits); 
 
});