【问题标题】:Filter json based on key and match it against one of the values from array [duplicate]根据键过滤json并将其与数组中的一个值匹配[重复]
【发布时间】:2021-12-27 17:55:34
【问题描述】:

我有 json 文件:products.json:

[
{
"id": "1",
"category": "Fruit from USA",
"name": "Banana",
},
{
"id": "2",
"category": "Fruit from Brazil",
"name": "Long Banana",
},
{
"id": "3",
"category": "Vegetable",
"name": "Carrot",
},
{
"id": "4",
"category": "Car from USA",
"name": "Ford",
},
{
"id": "5",
"category": "Car from Germany",
"name": "Audi",
},
{
"id": "6",
"category": "Train from Italy",
"name": "Pendolino",
},
]

然后我有一个数组

testMatch.match: ['Car', 'Fruit'].

我想过滤掉 products.json 以仅返回类别以 ES6 中 matchCategory 的任何元素开头的对象

我目前拥有的是:

const productList = products.filter(filteredCategory => filteredCategory.category.startsWith(testMatch.match));

但如果 testMatch.match 中有超过 1 个元素并且没有元素,则它不起作用 - 它返回所有产品而不是无。

【问题讨论】:

  • 您只需要扩展您当前的代码,1. 添加一个检查它是否是一个数组。 2. 遍历 testMatch.match 并查找是否有任何类别以它开头。

标签: javascript arrays


【解决方案1】:

您也可以使用Array#some 迭代match 并在查找时退出。

const
    products = [{ id: "1", category: "Fruit from USA", name: "Banana" }, { id: "2", category: "Fruit from Brazil", name: "Long Banana" }, { id: "3", category: "Vegetable", name: "Carrot" }, { id: "4", category: "Car from USA", name: "Ford" }, { id: "5", category: "Car from Germany", name: "Audi" }, { id: "6", category: "Train from Italy", name: "Pendolino" }],
    match = ['Car', 'Fruit'],
    productList = products.filter(({ category }) =>
        match.some(m => category.startsWith(m))
    );

console.log(productList);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    使用Array.some() 测试它是否以testMatch.match 中的任何字符串开头。

    const products = [{
        "id": "1",
        "category": "Fruit from USA",
        "name": "Banana",
      },
      {
        "id": "2",
        "category": "Fruit from Brazil",
        "name": "Long Banana",
      },
      {
        "id": "3",
        "category": "Vegetable",
        "name": "Carrot",
      },
      {
        "id": "4",
        "category": "Car from USA",
        "name": "Ford",
      },
      {
        "id": "5",
        "category": "Car from Germany",
        "name": "Audi",
      },
      {
        "id": "6",
        "category": "Train from Italy",
        "name": "Pendolino",
      },
    ];
    
    const testMatch = {
      match: ['Car', 'Fruit']
    };
    
    const productList = products.filter(filteredCategory =>
      testMatch.match.some(match => filteredCategory.category.startsWith(match)));
    
    console.log(productList);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 2019-09-09
      • 2021-09-02
      相关资源
      最近更新 更多