Access deeply nested objects, without the long ‘if’ conditions, using Reduce
Often we fall in a situation where we need to access a key in the object, then we end up testing the existence of that key in the object and then access it, for this we might end up doing something like below
This looks bad. Especially when the objects are deeply nested, testing the existence of each key clutters the readability of code.
Instead we can write a function which accepts the object and the path of the key in that object as the arguments and returns the value of the key if it exists or null if it does not exists.
Lets give it a shot. First lets have our JSON response which gives you the list of orders a user has placed in our website
let userOrder = {
user: {
orders: [
{ state: "dispatched" , price: 2333 },
{ state: "delivered" , price: 3333 },
{ state: "delivered" , price: 444 },
...
]
}
}
Now I need to access the latest order in the array of orders, the path for the same goes like
let objPath = ["user", "orders", 0 , "state"]
Now lets write the function
const findTheObjectKey = (path, obj) =>
path.reduce((acc, cur) =>
acc[cur] ? acc[cur] : null
, obj)
findTheObjectKey is an arrow function which returns the value from the return value of reduce function. Now when I run this
let res = findTheObjectKey(objPath, userOrder);
console.log(res);
Output of the above would be “dispatched”.
To explain the above, we are applying reduce function on the path array.
First time acc will be the object that we pass, cur will be the path[0] so we test userOrder[“user”] exist or not, if it exist then we return user object back, so second loop acc will be user object and cur will be path[1], again we test and the loop cont…
Explanation on the above reduce function in my other post https://medium.com/@spoo.naidu/js-reduce-function-6841c0f7c0ff