[英]Javascript/AngularJs - How do I fill an array with objects from another array?
Something I'm trying to do in an angularjs app that I'm making. 我正在尝试制作的angularjs应用中要做的事情。 I have a large array of the cast of a movie including directors, producers, film crew etc. and I want to make a new array of just the director(s). 我有各种各样的电影演员,包括导演,制片人,电影摄制组等,我想制作一系列仅由导演组成的电影。
I don't know how to fill a new array with specific objects form another array. 我不知道如何用另一个数组中的特定对象填充新数组。 Here's a quick simple example of what I mean: 这是我的意思的简单示例:
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*/
}
}
Please help! 请帮忙! Thank you! 谢谢!
try this: 尝试这个:
for(i = 0; i < products.length; i++) {
if (products[i].category == "fruit") {
fruits.push(products[i].name)
}
}
Try with this code this may do helpful for you 尝试使用此代码可能对您有帮助
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);
Use the filter
API: 使用filter
API:
this.fruits = this.products.filter(function(product) {
return product.category == 'fruits';
});
You can do this as follows: 您可以按照以下步骤进行操作:
this.fruits = this.products.filter(p => p.category == "fruit").map(p => p.name);
The .filter()
method takes only the objects with the right category. .filter()
方法仅采用具有正确类别的对象。 Then .map()
goes through this result, and replaces the objects by the name property value only, so that the final result is ["apple", "banana"]
. 然后.map()
遍历此结果,并仅用name属性值替换对象,因此最终结果为["apple", "banana"]
。
If you want the objects as a whole, then of course you leave out the .map()
part. 如果您需要整个对象,那么当然可以省略.map()
部分。
Demo: 演示:
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.