通过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 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西