1.有一个对象数组A,获取数组中指定类型的对象放到B数组中
// ES6
var products = [{
name: "苹果",
type: "水果"
}, {
name: "西蓝花",
type: "蔬菜"
}, {
name: "菠萝",
type: "水果"
}];
var newProducts = products.filter(function(pro){
return pro.type === "蔬菜"
})
console.log(newProducts);
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcugDN4UDMzgTM5ADNwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
var products = [{
name: "苹果",
type: "水果"
}, {
name: "西蓝花",
type: "蔬菜"
}, {
name: "菠萝",
type: "水果"
}];
var newProducts = [];
for(var i = 0; i < products.length; i++){
if(products[i].type === "蔬菜"){
newProducts.push(products[i]);
}
}
console.log(newProducts);
2.有一个对象数组A,过滤掉不满足以下条件的对象
条件:水果 数量大于0,价格小于10
var products = [{
name: "苹果",
type: "水果",
price:15,
quantity:2
}, {
name: "西蓝花",
type: "蔬菜",
price:5,
quantity:2
}, {
name: "菠萝",
type: "水果",
price:5,
quantity:2
}];
var newProducts = products.filter(function(pro){
return pro.type === "水果" && pro.price < 10 && pro.quantity > 0;
})
console.log(newProducts); // [{name: "菠萝", type: "水果", price: 5, quantity: 2}]
3.有两个数组A,B,根据A中的id值,过滤掉B数组中不符合的数据
var arr = {name: "苹果", type: "水果", price:15, quantity:2}
var products = [{
name: "苹果",
type: "水果",
price:15,
quantity:2
}, {
name: "西蓝花",
type: "蔬菜",
price:5,
quantity:2
}, {
name: "菠萝",
type: "水果",
price:5,
quantity:2
}];
var newProducts = products.filter(function(pro){
return pro.name === arr.name;
})
console.log(newProducts); // [{name: "苹果", type: "水果", price: 15, quantity: 2}]