[英]Check if an array contains an object with a certain property value in JavaScript?
如果我有類似的東西
[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
以避免跳過索引。
arr = arr.filter(function (item) {
return (item.name !== 'zipCode');
});
var i = array.length;
while(i-- > 0) {
if (array[i].name === "zipCode")
array.splice(i, 1);
}
yourArray.splice(index,1)
其拼接起來;然后:
由於在數組上做原型是不好的實踐而更新了這個答案,所以讓使用該建議的人在這里編寫更好的代碼是一個更好的選擇:
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)
可以在此處找到並測試新代碼
這也可以通過陣列上的原型來完成
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
代碼也可以在
這里找到並測試
這可能是一個詳細且簡單的解決方案。
//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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.