I am a beginner. I am trying to remove object "Bil' from 'zubi' (object array). Could anyone guide me?
var zubi=[
{a:1,b:1,c:1},
{a:2,b:2,c:2}
]
var Bil={a:1,b:1,c:1}
// the methods I tried which donot work :(
zubi.splice(zubi.indexOf(Bil),1)
zubi=zubi.filter(d=> d!==Bil)
-
@ Zubair, you can use JSON.stringify and filter as shown in the answer. Kindly checkBeginner– Beginner2020年01月13日 13:04:51 +00:00Commented Jan 13, 2020 at 13:04
3 Answers 3
JavaScript objects cannot be compared with equality operator (==).
You can achieve the comparison using deep-equal library:
var equal = require('deep-equal');
zubi=zubi.filter(d=> equal(d, Bil) === false)
underscore.isEqual does the same, you might use that library if you prefer.
Alternatively, in case you do not want to add dependencies to your project, you can compare each property by yourself, as adviced in another answer.
The code would then be:
zubi=zubi.filter(d=> d.a !== Bil.a && d.b !== Bil.b && d.c !== Bil.c);
Comments
You can use filter and JSON.stringify like shown below, So the output will have the array element without Bil Object.
@Update
This approach can be used if the keys order has not changed. Thanks to mehdi for pointing out this one.
var zubi=[
{a:1,b:1,c:1},
{a:2,b:2,c:2}
]
var Bil={a:1,b:1,c:1}
let output = zubi.filter(o => JSON.stringify(o) !== JSON.stringify(Bil))
console.log(output)
2 Comments
JSON.stringify. Source: Why You Shouldn’t Use JSON.stringify to Compare Objects in JavaScript.Each object is uniquely stored even they have same values means:
{a:1} === {a:1} // false
So, in your second case you can check the properties of the object to filter:
zubi=zubi.filter(d=> d.a !== Bil.a);
var zubi=[
{a:1,b:1,c:1},
{a:2,b:2,c:2}
]
var Bil={a:1,b:1,c:1}
// the methods I tried which donot work :(
zubi=zubi.filter(d=> d.a !== Bil.a)
console.log(zubi);