johni
johni

Reputation: 5568

Javascript's syntactic sugar for accessing object properties

I have a 'result' object that I'd like to pool the value of these nested properties.

Is there an elegant way to assign the values of these two properties if they exist and throw and error otherwise? I find myself writing some long code for doing such a simple operation.

Thanks

host: result["ServerCA"]["_"],
database: result["DBId"]["_"]

EDIT1 - more information

My code constructs an object that has the two properties host and database. The result object is a JSON containing some information. I can't guarantee that the JSON will actually contain these two properties _ under ServerCA and _ under DBId. As a matter of fact, I can't be sure that ServerCA and DBId will be defined in the result object.

So I'm trying to validate that these properties exist, and assign their value to my own object's two properties host and database.

How can I write this in the simplest way instead of writing 2 double IF statements?

Thanks...

Upvotes: 0

Views: 272

Answers (1)

madox2
madox2

Reputation: 51861

You can write a helper function to do this, for example:

function getOrThrow(obj, keys) {
    return keys.reduce(function(result, key) {
        if (!(typeof result === 'object') || !(key in result)) {
            throw new Error("property " + key + " does not exists");
        }
        return result[key];
    }, obj);
}

var result = {
    ServerCA: {
        _: "whatever"
    }
};

console.log(getOrThrow(result, ["ServerCA", "_"])); // whatever
console.log(getOrThrow(result, ["ServerCA", "_", "other"])); // throws error

Upvotes: 1

Related Questions