以 id 搜尋並從 JavaScript 中的 JSON 陣列中移除物件


假設有一個物件陣列,其中包含有關某些電影的資料,如下所示 −

const arr = [
   {id: "1", name: "Snatch", type: "crime"},
   {id: "2", name: "Witches of Eastwick", type: "comedy"},
   {id: "3", name: "X-Men", type: "action"},
   {id: "4", name: "Ordinary People", type: "drama"},
   {id: "5", name: "Billy Elliot", type: "drama"},
   {id: "6", name: "Toy Story", type: "children"}
];

我們需要編寫一個 JavaScript 函式,該函式將第一個引數作為此類陣列,第二個引數作為 id 字串。然後,我們的函式應透過該 id 搜尋物件,如果陣列中包含該物件,我們應從陣列中移除該物件。

示例

程式碼如下 −

const arr = [
   {id: "1", name: "Snatch", type: "crime"},
   {id: "2", name: "Witches of Eastwick", type: "comedy"},
   {id: "3", name: "X-Men", type: "action"},
   {id: "4", name: "Ordinary People", type: "drama"},
   {id: "5", name: "Billy Elliot", type: "drama"},
   {id: "6", name: "Toy Story", type: "children"}
];
const removeById = (arr, id) => {
   const requiredIndex = arr.findIndex(el => {
      return el.id === String(id);
   });
   if(requiredIndex === -1){
      return false;
   };
   return !!arr.splice(requiredIndex, 1);
};
removeById(arr, 5);
console.log(arr);

輸出

控制檯輸出將如下所示 −

[
   { id: '1', name: 'Snatch', type: 'crime' },
   { id: '2', name: 'Witches of Eastwick', type: 'comedy' },
   { id: '3', name: 'X-Men', type: 'action' },
   { id: '4', name: 'Ordinary People', type: 'drama' },
   { id: '6', name: 'Toy Story', type: 'children' }
]

更新日期: 21-11-2020

3K+ 瀏覽量

事業起航

完成課程即可獲得認證

開始吧
廣告