如何按 ID 从 JSON 个对象数组中删除数组元素

How to delete array element from JSON array of objects by ID

这可能很容易,但给我带来了麻烦。鉴于此 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"
        ]
      }
    ]

如何通过 key/value 从数组中删除一个对象?在这种情况下,通过 ID? playlist.splice(1,1)? playlist.delete(id)?不知道如何优雅地做到这一点。假设我想删除 ID = 3 的元素,如何得到这个结果:

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


使用Array.filter,您可以过滤掉不符合特定条件的元素。例如:

const result = playlists.filter(playlist => playlist.id !== '2');

这是一个工作演示:

/* Example Data */
const playlists = [
  {
    "id" : "1",
    "owner_id" : "2",
    "song_ids" : [ "8", "32"]
  },
  {
    "id" : "2",
    "owner_id" : "3",
    "song_ids" : ["6", "8","11" ]
  }
];

/* Takes a list of playlists, and an ID to remove */
const removePlaylistById = (plists, id) =>
  plists.filter(playlist => playlist.id !== id);

/* Removes playlist ID 2 from list, prints result */
const result = removePlaylistById(playlists, '2');
console.log(result);


另一种选择是使用 Array.findIndex to get the index of an element with given ID, then use Array.splice 删除该元素。这将修改数组,而不需要复制。

例如:

const indexToRemove = playlists.findIndex((pl) => pl.id === '2');
playlists.splice(indexToRemove, 1);