以 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' }
]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP