Trajce12
Trajce12

Reputation: 331

How can i check for null property in object inline with ES 6 syntax?

I have one object with five properties and i need to take just three of them.For one of the properties i need to check if it is null value then it should be 'Unknown'. The code will look like this

let obj = {
    name:"john",
    lastName:"doe",
    age:24,
    city:null

}

function getSomeProperties(obj) {
    let newObj = {
        name: obj.name,
        age:obj.age,
        city:obj.city == null ? 'unknown' : obj.city
    }
    console.log(newObj);
}

getSomeProperties(obj);

if i try to take only three properties inline then this works


function getSomeProperties(obj) {
    const newObj = (({name, age, city}) => ({name, age, city }))(obj);
    console.log(newObj);
}

but the problem is when i try inline to check if city is null like in the first case then i get error.

function getSomeProperties(obj) {
    const newObj = (({name, age, city}) => ({name, age, city == null ? 'unknown' : city }))(obj);
    console.log(newObj);
}

Can be this thing maked inline?

Upvotes: 0

Views: 257

Answers (1)

Ilijanovic
Ilijanovic

Reputation: 14904

You need to check it like this:

({name, age, city: city == null ? 'unknown' : city })

Or you use nullish coalescing operator:

({name, age, city: city ?? 'unknown' })

The same you can do above:

city: obj.city ?? 'unknown'

It checks if the left side is either null or undefined. If its the case it returns the value thats on the right side.

Remember 0 or false is not considered as nullish value.

In JavaScript, a nullish value is the value which is either null or undefined. Nullish values are always falsy.

Upvotes: 1

Related Questions