以 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+ 浏览量

事业起航

完成课程即可获得认证

开始吧
广告
© . All rights reserved.