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" }]
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.
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)
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. With a ?? b, either a or b will be returned. If a is undefined, null, then b will be returned. Otherwise, a will be returned. You can read more about it on MDN.