Javascript/AngularJs-如何用另一个数组中的对象填充数组

Javascript/AngularJs - How do I fill an array with objects from another array?

本文关键字:数组 对象 填充 另一个 AngularJs- 何用 Javascript      更新时间:2023-09-26

我正试图在我正在制作的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);
});