Javascript/AngularJs-如何用另一个数组中的对象填充数组
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*/
}
}
请帮忙!非常感谢。
尝试使用此代码,这可能会对有所帮助
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);
试试这个:
for(i = 0; i < products.length; i++) {
if (products[i].category == "fruit") {
fruits.push(products[i].name)
}
}
使用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()
遍历该结果,并仅用名称属性值替换对象,因此最终结果为["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);
});
相关文章:
- 将数组对象传递到struts2中的操作类
- 如何使用jquery返回php-json数组对象
- 从其名称获取javascript数组对象
- 值未与数组对象绑定
- 如何按数组/对象值的倍数过滤对象数组
- 在表中显示数组对象
- 在数组对象中分组
- 将第二个或多个数组推送到数组对象 AngularJS 中
- 重新排列 JavaScript 数组/对象
- 键上的javascript数组对象过滤器
- handontable:在不更改数据数组/对象的情况下隐藏某些列
- 用于跟踪购物车可用性的Javascript数组/对象/哈希表
- 重建有角度的java脚本数组对象
- 对JSON数组对象进行排序
- 连接与数组对象相关的文本:方式和位置
- 哪些浏览器和版本支持将常见的类数组对象直接传递到fn.apply()
- 如何使用Handlebars循环数组对象和模板
- 是否可以引用JS数组/对象中的另一个元素
- Javascript中的名称索引-数组/对象
- 数组长度不等于数组对象