Reputation: 373
I have an nodejs
application that serves data about systems, each system have a number of contact persons which are of the type employee.
Whenever someone requests a system I have a script that populates the employees which is related to the system.
The code I have now looks like this:
if(row.system_owner){
row.system_owner=emps[(row.system_owner).toUpperCase()];
}
if(typeof(row.system_owner) !== 'object'){
row.system_owner = null;
}
Where row is an instance of system, and emps is an object containing all employees. The reason for this is that initially a system only contains a reference to an employee, but here the reference is swapped for the entire employee object.
The code works great, but I was wondering if it is possible to make it a one liner, more like this, and skip the second IF statement
?
if(row.system_owner){
row.system_owner=emps[(row.system_owner).toUpperCase()] ? Object
: null
}
Upvotes: 0
Views: 59
Reputation: 143
you could also try using turnary operator in a following way:
if(row.system_owner){
row.system_owner = typeof(row.system_owner) === 'object'
? emps[(row.system_owner).toUpperCase()]
: null;
}
I can imageine that this is what you wanted to achieve with your proposal.
Upvotes: 0
Reputation: 4656
you can use &&
and ||
operators
b = {
key: 'value'
}
a = undefined
res = a && b[a]
console.log(res) // undefined
a = 'key'
res = a && b[a]
console.log(res) // 'value'
//if you need null, you can use || operator
a = undefined
res = a && b[a] || null
console.log(res) // null
In your case
row.system_owner=row.system_owner && emps[(row.system_owner).toUpperCase()]
Upvotes: 3