0

I have an Object with the following structure :

obj.food[drinks.category][drinkID].value

I want to be able to check all the properties - so that i won't receive errors.

I was thinking to create a function that's receives the object - convert it into string path and then loops evaluate each property - like this:

function validObj(obj){

let objPathStr = obj // can figure out how to do it
let objPathArr = objPathStr.split('[');
// loop over the paths and check if each has property with hasOwnProperty()

}

validObj(obj.food[drinks.category][drinkID].value)
RoyBarOn
  • 919
  • 3
  • 24
  • 63
  • It sounds like you're after [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)? I wrote [this](https://stackoverflow.com/questions/58297020/how-to-check-for-availability-for-a-nested-variable-without-checking-all-the-pre/58297408#58297408) answer recently and it might be what you're after? – Nick Parsons Dec 30 '19 at 11:42
  • @NickParsons Thanks - your solution is great - but how can i iterate over the object's properties? is your example you provide them as a parameter - i need to get them dynamically - so if i'll pass "foodObj.drinks.drinkType" the function will break each key and validate it.... – RoyBarOn Dec 30 '19 at 12:45

0 Answers0