猿问

试图通过它的特定元素从数组中删除对象

我得到了一个里面有对象的数组,这些对象里面有元素。我将如何通过元素之一来寻址这些对象之一?


let randomARR = [];


let a = {"name": "John", "age": 20, "PlaceOfBirth": "Germany"};

let b = {"name": "Simon", "age": 20, "PlaceOfBirth": "France"}; 

let c = {"name": "Michael", "age": 20, "PlaceOfBirth": "USA"};


randomARR.push(a);

randomARR.push(b);

randomARR.push(c);

结果:


[{"name": "John", "age": 20, "PlaceOfBirth": "Germany"}, {"name": "Simon", "age": 20, "PlaceOfBirth": "France"}, {"name": "Michael", "age": 20, "PlaceOfBirth": "USA"}]

假设我想通过对象的元素"name"寻址对象,而不是它在数组中的位置,将对象 b (name: Simon) 从数组中删除。


MYYA
浏览 133回答 2
2回答

繁星点点滴滴

您可以使用Array.prototype.filterfilter() 方法创建一个新数组,其中包含通过提供的函数实现的测试的所有元素。它遍历数组的所有元素,并根据布尔值返回将其从结果数组中保留/删除。您可以将其设置为当前数组以覆盖它。let objArr = [{"name": "John", "age": 20, "PlaceOfBirth": "Germany"}, {"name": "Simon", "age": 20, "PlaceOfBirth": "France"}, {"name": "Michael", "age": 20, "PlaceOfBirth": "USA"}]let newObj = objArr.filter(obj => obj.name !== "Simon");// objArr = objArr.filter(obj => obj.name !== "Simon"); to overwrite

慕哥9229398

randomARR = randomARR.filter(o => o.name != 'Simon') ;这是我认为要走的路。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答