0

I am parsing a complex object in Typescript, so have something like:

const a = reply['price']['value']['total']['value'];

and I like to ensure that all elements are defined in the chain, otherwise, it should set a=0 and do not trigger an exception if some of the chained keys are in fact undefined.

What would be the appropriate syntax for that?

2 Answers 2

4

If you're using modern JS you can use nullish coalescing and optional chaining

const a = reply?.['price']?.['value']?.['total']?.['value'] ?? 0;

Try to avoid using || instead of ??, because that will give you 0, if the final value is any falsy value, like 0 or false.

If you don't want to use nullish coalescing, you can do this, which achieves the same.

const a = reply?.['price']?.['value']?.['total']?.['value'] ? reply['price']['value']['total']['value'] : 0;
Sign up to request clarification or add additional context in comments.

2 Comments

I think using || in this case is actually better. Considering the name is value, probably 0 is what you want and not false.
I guess it could be reasoned that if the value is false, and we are checking for the value, false is what they actually want
0

If you can't use @nullptr 's answer, I suggest creating a function for that purpose :

function getObjectNestedValue2(obj, keys, defaultValue) {
    let currObjOrValue = obj;
    keys.forEach(key => {
        if (!currObjOrValue.hasOwnProperty(key)) {
            currObjOrValue = defaultValue;
            return;
        }
        currObjOrValue = currObjOrValue[key];
    });
    return currObjOrValue;
}

You then call it like so :

const a = getObjectNestedValue(reply, ['price', 'value', 'total', 'value'], 0);

Cheers

1 Comment

the question is tagged as typescript, so you'll have to provide the type for the function as well. the function you provided will throw errors if implicitAny is set to false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.