DEV Community

ADEKOLA Abdwahab
ADEKOLA Abdwahab

Posted on

4 3

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay