Angular, Find, and Push
Angular, Find, and Push
我有一个名为产品的数组,另一个名为主销售:
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)
相关文章:
- Selenium WebDriver and JavaScript change
- NodeJS API调用中Array中的Push和Pull元素
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Angular, Find, and Push
- Javascript .splice() and .push() error
- Push Woosh and PhoneGap 2.5.0 implimentation
- PUSH using PHP, Ajax and Javascript/jQuery?
- MongoDB Double Upsert and a Push