代码之家  ›  专栏  ›  技术社区  ›  Rachel

如何使用数组。filter()在JSON对象数组中搜索键值

  •  0
  • Rachel  · 技术社区  · 4 年前

    如果我有一个像这样的对象数组 playlists.json

    "playlists" : [
          {
            "id" : "1",
            "owner_id" : "2",
            "song_ids" : [
              "8",
              "32"
            ]
          },
          {
            "id" : "2",
            "owner_id" : "3",
            "song_ids" : [
              "6",
              "8",
              "11"
            ]
          },
          {
            "id" : "3",
            "owner_id" : "7",
            "song_ids" : [
              "7",
              "12",
              "13",
              "16",
              "2"
            ]
          }
        ]
    

    在Node中,我在文件中读到如下内容:

    const data = JSON.parse(fs.readFileSync('playlists.json'));
    

    我想写一封信 .filter() 可以通过 id 并将结果变异为一个新数组,从而删除测试的条目。

    当然,我们可以这样访问索引: playlists[0].id);

    你会怎么写 .filter() 测试 身份证件 i、 e.生成一个新的数组并移除值?(变种)我在下面写了一些代码,但它是错误的。

    const someId = "2"
    const result = playlists.filter(playlist => playlist.id !== someId)
    

    新系列 result 将包括:

    "playlists" : [
          {
            "id" : "1",
            "owner_id" : "2",
            "song_ids" : [
              "8",
              "32"
            ]
          },
          {
            "id" : "3",
            "owner_id" : "7",
            "song_ids" : [
              "7",
              "12",
              "13",
              "16",
              "2"
            ]
          }
        ]
    
    2 回复  |  直到 4 年前
        1
  •  1
  •   Arky Asmal    4 年前

    您使用了filter fine,但是,您已经从json对象中选择了密钥。 下面是一个例子。

     const jsonFile = {
            "playlists" : [
                  {
                    "id" : "1",
                    "owner_id" : "2",
                    "song_ids" : [
                      "8",
                      "32"
                    ]
                  },
                  {
                    "id" : "2",
                    "owner_id" : "3",
                    "song_ids" : [
                      "6",
                      "8",
                      "11"
                    ]
                  },
                  {
                    "id" : "3",
                    "owner_id" : "7",
                    "song_ids" : [
                      "7",
                      "12",
                      "13",
                      "16",
                      "2"
                    ]
                  }
                ]
            }
            const someId = 2
            const result = jsonFile.playlists.filter(playlist => playlist.id !== someId)
            console.log(result)
    
        2
  •  0
  •   Rachel    4 年前

    经过一些检查。我需要在播放列表中使用父对象引用来获得正确的结果,如下所示:

    const someId = "2";
    const result = data.playlists.filter(playlist => playlist.id !== someId)
    console.log(result);