【问题标题】:filter array in propsprops 中的过滤器数组
【发布时间】:2021-07-19 06:43:00
【问题描述】:

我一直在过滤 nextjs 页面中道具中的对象数组时遇到问题。我正在使用下面的 json 和编码。

[
{
    "id": "1",
    "name": "name1",
    "category": ["food"]
},
{
    "id": "2",
    "name": "name2",
    "category": ["food", "beverages"]
}]
import React from "react";

const test2 = ({ prods }) => {
    return (
        <div>
            <div>
                {prods
                    .filter((product) => product.category.includes("eve"))
                    .map((filterarray) => (
                        <li>
                            {filterarray.id}
                            {filterarray.name}
                            {filterarray.category}
                        </li>
                    ))}
            </div>
        </div>
    );
};

export async function getStaticProps() {
    const prods = (await import("./product.json")).default;
    return {
        props: {
            prods,
        },
    };
}
export default test2;

列出完整的数组有效。 (数据为 1 个字符串,例如“foodbeverage”,但我认为应该还可以) 过滤 id 工作正常。但是当我尝试使用 include 它不再显示任何结果。 如果有人能指出我做错了什么。或者如果我更好地采用不同的方法,任何帮助将不胜感激。

【问题讨论】:

    标签: arrays reactjs filter next.js


    【解决方案1】:

    Array#includes() 不进行部分匹配。您需要在数组中的每个元素上使用String#includes()

    您可以通过在过滤器中使用Array#some() 来做到这一点。

    prods.filter((product) => product.category.some(cat=>cat.includes("eve")))
    

    【讨论】:

      【解决方案2】:

      您需要在category 数组上将include 替换为some

      let prods = [
        {
          id: "1",
          name: "name1",
          category: ["food"]
        },
        {
          id: "2",
          name: "name2",
          category: ["food", "beverages"]
        }
      ];
      
      let result = prods.filter((product) =>
        product.category.some((pro) => pro.includes("eve"))
      );
      console.log(result);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-10
        • 2019-08-08
        • 2022-08-11
        • 2020-02-24
        • 2018-03-02
        • 2018-04-26
        • 2017-06-05
        • 2020-09-21
        相关资源
        最近更新 更多