I am trying to remove object if object matches, I dont want to compare any object key, I just want to compare whole object with array of object, and if it matches, then I have to remove that object from original array.
let originalArray = [
{name: 'abc', country: 'eng'},
{name: 'xyz', country: 'ind'},
{name: 'pqr', country: 'us'}
]
let objectToBeRemove = [
{name: 'pqr', country: 'us'}
]
console.log(originalArray);
Expected output:
[
{name: 'abc', country: 'eng'},
{name: 'xyz', country: 'ind'}
]
I am not able to figure out how can I compare object, I can do it by id or any key, but I am making generic thing, so may be in few cases ID is not present, that's why I want to compare object
One way is to use Array#filter with Array#some + JSON.stringify() for comparison.
Note that Array#filter returns a new array. So the variable needs to be reassigned.
let originalArray = [
{name: 'abc', country: 'eng'},
{name: 'xyz', country: 'ind'},
{name: 'pqr', country: 'us'}
];
let objectToBeRemove = [
{name: 'pqr', country: 'us'}
];
originalArray = originalArray.filter(obj =>
objectToBeRemove.some(objToRemove =>
JSON.stringify(objToRemove) !== JSON.stringify(obj)
)
);
console.log(originalArray);
Note: Using JSON.stringify() is a little primitive for object comparison in my opinion. For instance the check would fail if the properties are in different order {country: 'us', name: 'pqr'}. Better way would be to do a deep comparison. For eg. using _.isEqual from loadash library. See here for more info.
Using loadash
let originalArray = [
{name: 'abc', country: 'eng'},
{name: 'xyz', country: 'ind'},
{name: 'pqr', country: 'us'}
];
let objectToBeRemove = [
{country: 'us', name: 'pqr'}
];
originalArray = originalArray.filter(obj =>
objectToBeRemove.some(objToRemove =>
!_.isEqual(objToRemove, obj)
)
);
console.log(originalArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You can use "filter" function to do that: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var myArr = [{name: "toto"}, {name: "tata"}, {name: "tutu"}];
var toRemove = {name: "tata"};
let ret = myArr.filter(function(el) {
return el.name != toRemove.name;
});
Or for removing multiple items:
var myArr = [{name: "toto"}, {name: "tata"}, {name: "tutu"}];
var toRemove = [{name: "tata"}, {name: "tutu"}];
for (var i = 0; i < toRemove.length; i++) {
let index = myArr.findIndex((el) => { // Search item index to remove
return el.name == toRemove[i].name;
});
if (index != -1) myArr.splice(index, 1); // Remove item in found index
}
To compare the equality of the complete object you could use the JSON.stringify() method.
Example;
JSON.stringfy(originalArray[i]) === JSON.stringfy(objectToBeRemove)