DEV Community

Rahul kumar
Rahul kumar

Posted on

Create Object with dynamic property name in javaScript([name]:val)

What can you do?

const obj = {
  "name":val
}

// to
const prop = "name";
const obj = {
  [prop]:val
}
Enter fullscreen mode Exit fullscreen mode

With new javaScript, you can create object by assigning dynamic properties to it.

Use Case

You have following document in your MongoDB collection

{
   name:"Rahul kumar",
   title:"....",
   body:"..",
   tags:[...],
   date:"..",
   createdAt:"...",
   editedAt:"..",
   ....more
}
Enter fullscreen mode Exit fullscreen mode

If you know MongoDB then you might have modified any attribute of document.

In this case, we need to write query like below,

db.collection.update({...filter},{
  $set:{
    attributeName:"value...",
    // like
    title:"....",
  }
});
Enter fullscreen mode Exit fullscreen mode

If you are not using dynamic property feature, then you might be creating different express routes and different functions to edit name, title, body and so on..

But, do you know you can do this in just single function?

Yeah, here we can use dynamic property names..

function update(attr,data){
db.collection.update({...filter},{
  $set:{
    [attr]:data
  }
});
} 
Enter fullscreen mode Exit fullscreen mode

Now, you can pass any string as attribute name and data to edit the value.

There might be more use cases which you can comment below.

Thanku

Top comments (0)