如何从数组中删除对象? 我希望从someArray中删除包含名称Kristian的对象。例如:

someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];

我想实现:

someArray = [{name:"John", lines:"1,19,26,96"}];

当前回答

在你的数组语法中似乎有一个错误,所以假设你的意思是一个数组,而不是一个对象,数组。Splice是你的朋友:

someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)

其他回答

如果你在数组中的对象上没有任何你知道的属性(或者可能是唯一的),但是你有一个你想要删除的对象的引用,你可以执行下面unregisterObject方法中的操作:

let registeredObjects = []; function registerObject(someObject) { registeredObjects.push(someObject); } function unregisterObject(someObject) { registeredObjects = registeredObjects.filter(obj => obj !== someObject); } let myObject1 = {hidden: "someValue1"}; // Let's pretend we don't know the hidden attribute let myObject2 = {hidden: "someValue2"}; registerObject(myObject1); registerObject(myObject2); console.log(`There are ${registeredObjects.length} objects registered. They are: ${JSON.stringify(registeredObjects)}`); unregisterObject(myObject1); console.log(`There are ${registeredObjects.length} objects registered. They are: ${JSON.stringify(registeredObjects)}`);

你也可以使用地图功能。

someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John",lines:"1,19,26,96"}];
newArray=[];
someArray.map(function(obj, index){
    if(obj.name !== "Kristian"){
       newArray.push(obj);
    }
});
someArray = newArray;
console.log(someArray);

最简单的解决方案是创建一个映射,按名称存储每个对象的索引,如下所示:

//adding to array
var newPerson = {name:"Kristian", lines:"2,5,10"}
someMap[ newPerson.name ] = someArray.length;
someArray.push( newPerson );

//deleting from the array
var index = someMap[ 'Kristian' ];
someArray.splice( index, 1 );

你也可以用一些:

someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];

someArray.some(item => { 
    if(item.name === "Kristian") // Case sensitive, will only remove first instance
        someArray.splice(someArray.indexOf(item),1) 
})

在数组上使用splice函数。指定开始元素的位置和要删除的子序列的长度。

someArray.splice(pos, 1);