Angular, Find, and Push

Angular, Find, and Push

本文关键字:Push and Find Angular      更新时间:2023-09-26

我有一个名为产品的数组,另一个名为主销售

sells = [];
products = [
  {id:1, name:'something', price:30},
  {id:2, name:'something', price:30},
  {id:2, name:'something', price:30},
  {id:3, name:'something', price:30}
]

给定一个产品id,我想从产品中获取一个条目,并将其附加到销售。我该怎么做?

当您使用map时,您无法初始化sells = [];,因为map总是返回数组。但当您初始化sells = [];时,您当然可以使用forEach:

products.forEach(function(product) {
    if (product.id === 5)
         sells.push(product);
});

在lodash或下划线中可以找到很多很酷的find、where、map和其他功能

假设可以有多个条目具有相同的id,您可以使用map函数返回一个由具有特定id的所有条目组成的数组,如下所示:

假设,我们要查找与id == 2、相关的所有条目

var id_arr = products.map(function(entry) {
                 if(entry.id == 2) {
                     return entry  
                 }
             })

现在,id_arr包含所有具有id == 2的条目。现在使用concat添加到sells阵列:

sells = sells.concat(id_arr)