如果我有这样的内容: ,那么...
[Object(id:03235252, name:"streetAddress"), Object(id:32624666, name:"zipCode")...]
如何从该数组中删除名称设置为“zipCode”的对象?
[Object(id:03235252, name:"streetAddress"), Object(id:32624666, name:"zipCode")...]
如何从该数组中删除名称设置为“zipCode”的对象?
splice()
。for (var i = array.length - 1; i > -1; i--) {
if (array[i].name === "zipCode")
array.splice(i, 1);
}
注意我是在反向循环。这是为了应对 .splice(i, 1)
后数组将被重新索引的情况。.splice()
时都需要调整 i
,以避免跳过索引。由于在数组上进行原型设计是不好的实践,因此我更新了这个答案,为了让使用该建议的人编写更好的代码,这里提供了更好的选择:
const myArr = [
{
name: "lars",
age: 25
}, {
name: "hugo",
age: 28
}, {
name: "bent",
age: 24
}, {
name: "jimmy",
age: 22
}
];
const findAndRemove = (array, prop, value) => {
return array.filter((item) => item[prop] !== value);
}
const newArr = findAndRemove(myArr, 'name', 'jimmy')
console.log(newArr)
// Could also be simply written like this:
const otherArr = myArr.filter(item => item.name !== 'jimmy')
可以在这里找到和测试新代码。
也可以通过数组原型来实现此操作
Array.prototype.containsByProp = function(propName, value){
for (var i = this.length - 1; i > -1; i--) {
var propObj = this[i];
if(propObj[propName] === value) {
return true;
}
}
return false;
}
var myArr = [
{
name: "lars",
age: 25
}, {
name: "hugo",
age: 28
}, {
name: "bent",
age: 24
}, {
name: "jimmy",
age: 22
}
];
console.log(myArr.containsByProp("name", "brent")); // Returns false
console.log(myArr.containsByProp("name", "bent")); // Returns true
这里可以找到和测试代码链接
var i = array.length;
while(i-- > 0) {
if (array[i].name === "zipCode")
array.splice(i, 1);
}
yourArray.splice(index,1)
将其删除;然后,要么:
这可能是一个详细而简单的解决方案。
//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
{
// value exists in array
//write some codes
}
// array with objects
var arr = [
{x:'a', y:'b'},
{x:'p', y:'q'}
];
// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
if (elm.x == 'p')
{
return elm; // returns length = 1 (object exists in array)
}
});
// or y:'q' exists in arr
var check = arr.filter(function (elm){
if (elm.y == 'q')
{
return elm; // returns length = 1 (object exists in array)
}
});
// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
if (elm.x == 'p' && elm.y == 'q')
{
return elm; // returns length = 1 (object exists in array)
}
});
// in all cases
console.log(check.length); // returns 1
if (check.length > 0)
{
// returns true
// object exists in array
//write some codes
}