![](/img/trans.png)
[英]In JavaScript, how do I merge an array of objects with another array of objects?
[英]Javascript/AngularJs - How do I fill an array with objects from another array?
我正在嘗試制作的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*/
}
}
請幫忙! 謝謝!
嘗試這個:
for(i = 0; i < products.length; i++) {
if (products[i].category == "fruit") {
fruits.push(products[i].name)
}
}
嘗試使用此代碼可能對您有幫助
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);
使用filter
API:
this.fruits = this.products.filter(function(product) {
return product.category == 'fruits';
});
您可以按照以下步驟進行操作:
this.fruits = this.products.filter(p => p.category == "fruit").map(p => p.name);
.filter()
方法僅采用具有正確類別的對象。 然后.map()
遍歷此結果,並僅用name屬性值替換對象,因此最終結果為["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); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.