DEV Community

ADEKOLA Abdwahab
ADEKOLA Abdwahab

Posted on

How to Use a Variable as an Object's Key and Sub key

I have a user object that I am updating my mongodb doc with.

The doc exists already, however, at a point of the user journey they would have to submit some details, claim details, which I want to go into just one field - claims.

That should not be a problem, but say for a particular issue, I want all the claims to be logged under our field claims, with usernames ( remember this would be a variable) as keys, like this:

image

To achieve that, you do not just say:

image

Mongo won't take that, it is even wrong in normal Javascript.

It should be in [brackets], like this:

image

Hmm..... but in the line above, there is a bug.

There will always be just one claim, as current claim will be overwritten.

So instead of having something like this:

image

You would have this:

image

To fix this:

We have to get our referencing right.

Our usernames are subkeys in the claims object.

In mongodb we can reference them -subkeys- by saying: claims.yourUserName, claims.myUserName. But this is not straightforward to update via our code.

There many tweaks that comes to mind readily, but this is the fix I found:

Bring the claims key object and username subkey together: claims|username, so this serves as our main key.

image

But what is the right syntax? Dot notation would not work right there. Our brackets would not as well.

You will have to create the key before we enter it into the mongo update code line.

    let claimObject = `claims.${userEmail}`;

Enter fullscreen mode Exit fullscreen mode

It is claimObject we will now use as object key, since for every userName, our claimObject would be:

claims.yourUserName
claims.myUserName
claims.herUserName
.
.
.
claims.NthUserName

Enter fullscreen mode Exit fullscreen mode

image

Na so e go be

Top comments (0)