我有一个数组,看起来像这样:

const subscriptions = [
    {
        "price": "20",
        "product": "apple",
        "quantity": 1,
    },
    {
        "price": "10",
        "product": "orange",
        "quantity": 1,
    },
    {
        "price": "10",
        "product": "orange",
        "quantity": 1,
    },
    {
        "price": "10",
        "product": "orange",
        "quantity": 1,
    },
]

我想用applebananapear的乘积来提取所有数组元素.

所以我用filter()个这样:

const currentPlans = subscriptions.filter(
  (subscription) =>
    subscription.product ===
    ('apple' || 'banana' || 'pear')
);

因为数组只有一个apple的实例,而currentPlans应该包含这个实例.

currentPlans返回的是一个空array.

我做错了什么?

推荐答案

下面这句话不会像你预期的那样奏效.右侧首先计算一个值(apple),然后判断是否相等.它从不判断bananapear.

subscription.product === ("apple" || "banana" || "pear")

您应该使用另一个数组来保存匹配项.试试下面的方法.

Using indexOf

const subscriptions = [ { price: "20", product: "apple", quantity: 1, }, { price: "10", product: "orange", quantity: 1, }, { price: "10", product: "orange", quantity: 1, }, { price: "10", product: "orange", quantity: 1, }, ];

const matches = ["apple", "banana", "pear"];

const currentPlans = subscriptions.filter(
  (subscription) => matches.indexOf(subscription.product) >= 0
);

console.log(currentPlans);

Using includes

 const subscriptions = [ { price: "20", product: "apple", quantity: 1, }, { price: "10", product: "orange", quantity: 1, }, { price: "10", product: "orange", quantity: 1, }, { price: "10", product: "orange", quantity: 1, }, ];

const matches = ["apple", "banana", "pear"];

const currentPlans = subscriptions.filter(
  (subscription) => matches.includes(subscription.product)
);

console.log(currentPlans);

Javascript相关问答推荐

使用print This时, map 容器已在LeafletJS中初始化

没有输出到带有chrome.Devtools扩展的控制台

使用下表中所示的值初始化一个二维数组

Angular material 拖放堆叠的牌副,悬停时自动展开&

使用useEffect,axios和useParams进行react测试

如何迭代叔父元素的子HTML元素

React.Development.js和未捕获的ReferenceError:未定义useState

更新动态数据中对象或数组中的所有值字符串

有效路径同时显示有效路径组件和不存在的路径组件

未捕获的运行时错误:调度程序为空

TypeORM QueryBuilder限制联接到一条记录

固定动态、self 调整的优先级队列

如何在移动设备中使用JAVASSCRIPT移除点击时的焦点/悬停状态

如何在Reaction中设置缺省值, Select 下拉列表,动态追加剩余值?

在HTML中使用meta标记来指定定制元数据以用于使用JavaScript进行检索是不是一个坏主意?

在执行console.log(new X())时记录一个字符串

将匿名函数附加到链接的onClick属性

如果未定义,如何添加全局变量

Node.js的Fetch()调用总是创建新的Express会话

为什么Reaction useEffect函数会将控制台日志(log)呈现两次