I have inserted objects with a new property(property name - "Type") to a JS array. After that, I need to filter objects with that property(which is "Type") to a new array.
var arr = [
{ID: 1, Name: "Name1"},
{ID: 2, Name: "Name2"}]
var newObject = {
ID: 3,
Name: 'Test',
Type: 'New'
};
arr.push(newObject);
I tried
var newVal = arr.filter(x => x.Type !== null);
it returns all the object from array
result should be
[{ ID: 3, Name: "Test", Type: "New" }]
CodePudding user response:
Don't check for null
. Use undefined
instead:
var newVal = arr.filter(x => x.Type !== undefined);
Check this definition of null
and undefined
:
Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript. Undefined: It means the value does not exist in the compiler. It is the global object.
CodePudding user response:
Because it is undefined instead of null
The code below will get any type EXCEPT falsy types like "Type" : 0
and "Type": ""
let arr = [
{ID: 1, Name: "Name1"},
{ID: 2, Name: "Name2"}]
var newObject = {
ID: 3,
Name: 'Test',
Type: 'New'
};
arr.push(newObject);
const newVal = arr.filter(x => {
console.log(x.Type)
return x.Type; // not undefined, not null, not empty string.
});
console.log(newVal)
CodePudding user response:
In newer versions of Javascript (ES 2021 I think), you can use nullish coalescing:
var arr = [
{ID: 1, Name: "Name1"},
{ID: 2, Name: "Name2"}]
var newObject = {
ID: 3,
Name: 'Test',
Type: 'New'
};
arr.push(newObject);
var newVal = arr.filter(x => x.Type ?? false);
console.log(newVal)
Nullish coalescing is good for when a variable is defined, but it is technically false. ""
and 0
will return true with nullish coalescing. undefined
, null
, and false
return false. You can read more about it on MDN.