Optional Chaining & Arrow Functions
You can use ?.
to avoid having to check null
s on properties. Also, you can use arrow functions to easily filter an array in JavaScript.
Here is some example code:
let list = [
{name: 'John Smith', age: 13},
{name: 'Peter Jones', age: 23},
{name: 'Jane Doe', age: 54},
{name: null, age : 12},
{age: 72}
];
let result = list.filter(i => {
return (
i.name?.startsWith("J") &&
i.age < 40
)
});
console.log(result);
// Returns only "John Smith"
Without Optional Chaining
As Makyen pointed out, you may not be able to us optional chaining. In that case you can just check each field before using it, as shown below.
let list = [
{name: 'John Smith', age: 13},
{name: 'Peter Jones', age: 23},
{name: 'Jane Doe', age: 54},
{name: null, age : 12},
{age: 72}
];
let result = list.filter(i => {
return (
i.name && // If 'name' is null the condition will fail fast
i.name.startsWith("J") &&
i.age < 40
)
});
console.log(result);
// Returns only "John Smith"
I found a function on a different question (https://stackoverflow.com/a/23809123/8779719) which allows you to easily check nested objects. I've slightly modified it to check for nested fields.
function get(obj, key){
return key.split(".").every(function(x) {
if(typeof obj != "object" || obj === null || ! x in obj || !obj[x])
return false;
obj = obj[x];
return true;
});
}
let list = [
{
name: {
firstName: 'John', lastName: 'Smith'
},
age: 13
},
{
name: {
firstName: null, lastName: 'Jones'
},
age: 23
},
{
name: {
lastName: 'Jones'
},
age: 46
}
];
let result = list.filter(i => {
return (
get(i, "name.firstName") &&
i.name.firstName.startsWith("J") &&
i.age < 40
)
});
console.log(result);
// Returns only "John Smith"
Links:
Optional chaining
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Arrow functions - a good article I wrote about arrow functions
https://dev.to/acroynon/javascript-arrow-functions-explained-3m04