Setting JSON node name to variable value


I've spent most of my time in languages like Java and C++ but I'm trying to pick up JavaScript. What I'm attempting to accomplish is a way to set the parent node name by the value of the variable passed. I am using Firebase if that makes a difference in this code but I didn't think it would.

var parent_node_name = "EPLU200";
var onComplete = function(error) {
  if (error) {
        console.log('Synchronization failed');
  } else {
        console.log('Synchronization succeeded');
  }
};

// update adds the data without replacing all of the other nodes
myFirebaseRef.update({
    parent_node_name: { // trying to change this part to not save as "parent_node_name" 
        id2: "1175",    // but instead as "EPLU200" 
        ...
  }
}, onComplete);

The action saves to my Firebase server just fine but the problem is passing the actual value of the variable instead of reading the variable name.

Is there any workaround in JavaScript? I tried searching for it but I didn't know what to call it.

Answer

Depending on the environment (i.e node?)

myFirebaseRef.update({
    [parent_node_name]: {
        id2: "1175",
        ...
  }
}, onComplete);

See the code commented as Computed property names (ES6) in New Notations in ES2015 doumentation at MDN

if that doesn't work, you have to do this

var obj = {};
obj[parent_node_name] = {
    id2: "1175",
    ...
};
myFirebaseRef.update(obj, onComplete);
source: stackoverflow.com
js interview questions