3

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.

Community
  • 1
  • 1
booky99
  • 1,436
  • 4
  • 27
  • 45
  • Possible duplicate of [Using a variable for a key in a JavaScript object literal](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal) – stdob-- Feb 14 '16 at 01:58
  • I realize it was extremely similar. I apologize for having such a close question. Didn't know they had a whole documentation dedicated to stuff like this – booky99 Feb 14 '16 at 02:07
  • As a side note: It's often good practice to disassociate parent node names from the data they contain - hard coding fixed names often leads to coding yourself into a corner. If you have a 'generic' node name then you can easily keep references to it in other nodes and if one of it's children needs to be updated, that can be done without having to update anywhere else the node is referenced. – Jay Feb 14 '16 at 13:58

1 Answers1

0

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);
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87