If I have something like
[Object(id:03235252, name:"streetAddress"), Object(id:32624666, name:"zipCode")...]
How can I remove an object from that array that has name set to "zipCode"?
Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false. Example: html.
isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false . Note: For an array, the typeof operator returns an object.
We are required to write a function containsAll() that takes in two arguments, first an object and second an array of strings. It returns a boolean based on the fact whether or not the object contains all the properties that are mentioned as strings in the array.
If you need to modify the existing Array, you should use splice()
.
for (var i = array.length - 1; i > -1; i--) {
if (array[i].name === "zipCode")
array.splice(i, 1);
}
Notice that I'm looping in reverse. This is in order to deal with the fact that when you do a .splice(i, 1)
, the array will be reindexed.
If we did a forward loop, we would also need to adjust i
whenever we do a .splice()
in order to avoid skipping an index.
arr = arr.filter(function (item) {
return (item.name !== 'zipCode');
});
Updated this answer due to doing prototypes on arrays are bad prac so to get people who use the suggestion to write better code here is a better option:
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')
New code can be found and tested here
This can also be done with a prototype on the array
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
Code can also be found and tested here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With