代码之家  ›  专栏  ›  技术社区  ›  Tom Bom

如何从json返回特定对象(不区分大小写)?

  •  0
  • Tom Bom  · 技术社区  · 6 年前

    我正在制作一个带有Express、PrestGRs和后缀的应用程序。

    我有一个json,如下所示:

    {
      "names": [
        {
          "id": 1,
          "name": "John",
          "surname": "Smith"
        },
        {
          "id": 2,
          "name": "Peter",
          "surname": "Black"
        },
        {
          "id": 3,
          "name": "Marie",
          "surname": "White"
        }
      ]
    }
    

    如果我在查询中写入它们的一个名称,不区分大小写,我想返回整个元素。

    例如,如果我查询 mari 我想回来:

    {
      "id": 3,
      "name": "Marie",
      "surname": "White"
    }
    

    像这样,我只能得到值,而不是整个条目(我需要id)

    const names = persons.map(a => a.name);
    const surnames = persons.map(a => a.surname);
    const namesSurnames = names.concat(surnames)
    const el = namesSurnames.find(a => a.includes(req.query.keyword));
    console.log('el:', el);
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   wobsoriano    6 年前

    你可以使用 .filter 方法和用途 .toLowerCase() includes 搜索关键字 mari 名字或姓氏的钥匙。

    const sample = {
      "names": [
        {
          "id": 1,
          "name": "John",
          "surname": "Smith"
        },
        {
          "id": 2,
          "name": "Peter",
          "surname": "Black"
        },
        {
          "id": 3,
          "name": "Marie",
          "surname": "White"
        }
      ]
    };
    
    const query = 'mari';
    const name = sample.names.filter((user) => {
      return user.name.toLowerCase().includes(query.toLowerCase()) || user.surname.toLowerCase().includes(query.toLowerCase());
    });
    
    if (name.length > 0) {
      console.log(name[0]);
    } else {
      console.error('NO NAME FOUND!');
    }