如何显示多个满足条件的数组元素?

时间:2019-01-17 18:13:20

标签: javascript typescript

如何在控制台中显示匹配条件的数组的多个值(例如===“ McDonalds”)?

我只设法显示一项。但是我不知道如何显示数组的所有值。

public products: product[] = [
    { id: 1, name: "McFlurry", price: 2, enseigne:"McDonalds" },
    { id: 2, name: "Potatoes", price: 3, enseigne:"McDonalds" },
    { id: 3, name: "BigMac", price: 4, enseigne:"KFC" },
    { id: 4, name: "Nuggets", price: 3, enseigne:"KFC" }
];


searchEnseigne(){
    let server = this.products.find(x => x.enseigne === "McDonalds");
    console.log(server);
}

2 个答案:

答案 0 :(得分:2)

 let server = this.products.filter(x => x.enseigne === "McDonalds");
 console.log(server);

答案 1 :(得分:0)

使用filter代替find

filter()方法使用所有通过测试的元素创建一个新数组。虽然find()方法返回第一个元素

的值
searchEnseigne(){
    let server = this.products.filter(x => x.enseigne === "McDonalds");
    console.log(server);
}