0
temp = temp[array[i]] = {name:value};

In the above snippet the name is actually a parameter to my function having a value first_name.

Here's the function.

function createHierarchy(obj, group, name, value){
    console.log("group = "+group+"\nname ="+name)
    var array = group.split(".");
    var temp = obj;
    var len  = array.length;
    for(var i = 0; i < len; i++) {
        if(temp[array[i]] === undefined)
            temp = temp[array[i]] = {name:value};
        else
            temp = temp[array[i]][name] = value;
    }
    return obj;
}

The object being dumped has the key name equal to the identifier passed not its dynamic value which was "first_name" .

What am i missing. Let me know if i should update something.

Actual output

name: "cafebabe"

Expected output

first_name : "cafebabe"

FYI

Call this function like

createHierarchy({}, 'personal_details', 'first_name', 'cafebabe')

cafebabe1991
  • 4,928
  • 2
  • 34
  • 42
  • @FelixKing: That's not the problem here. The problem is that the OP is setting a default value incorrectly. – Cerbrus Jul 14 '15 at 13:52

1 Answers1

1

This piece of code is incorrect, you can't use name as variable in a default value like that:

if(temp[array[i]] === undefined)
    temp = temp[array[i]] = {name:value};
else
    temp = temp[array[i]][name] = value;

Replace that with:

temp[array[i]] = temp[array[i]] || {}; // If `temp[array[i]]` doesn't exist, add it.
temp = temp[array[i]][name] = value;  // Assign the `value`.

JavaScript does not allow variables to be used as object keys, in object literals. In this example:

{ name: value }

JavaScript interpreters will never look for a name variable. It will just use "name" as the key.

The only way to use variables as object keys, is via the bracket notation:

myObject[name]
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Agreed. Also, there is no need to use `temp`, it stores a reference to the exact same instance, so you can just use `obj` the whole time as well. – Jim Buck Jul 14 '15 at 13:50
  • @JimmyBoh Using temp was because of something i did not disclose in this question for not going out of context.But here's my previous question that shows the need of temp variable. http://stackoverflow.com/questions/31390915/how-to-create-a-complex-nested-js-object-dynamically/31391352#31391352 – cafebabe1991 Jul 14 '15 at 13:52
  • @Cerbus , I want to know why the parameter's value is being instead of its identifier.Is it to do with how the js parser works ? Is there a place i can read it ? – cafebabe1991 Jul 14 '15 at 14:03
  • @cafebabe1991: I added a little explanation to the answer. – Cerbrus Jul 14 '15 at 14:07
  • Thanks i fixed it with what you said. – cafebabe1991 Jul 14 '15 at 14:12