通过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' }
]热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便