在 JavaScript 中按 id 搜索并从 JSON 数组中删除对象
javascriptweb developmentfront end technologyobject oriented programmingjson
假设我们有一个对象数组,其中包含有关某些电影的数据,例如 −
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' } ]