0

This question is purely syntax. I'm trying to insert a generated JSON object into another JSON object.

Let's say my JSON looks like this:

var database =
{
  "john": {
    "pwd": "somehashrighthere",
    "mail": "example@gmail.com"
  }
}

This object stores a hash and an email under the users name. Now I want to insert a new user:

var name = "somename";
var pwd = "hash";
var mail = "email@email.net";

If I try to insert this into a json object as by

database.name =
{
    "pwd": pwd,
    "mail": mail
}

I would expect an output that fills the gaps:

{
  "john": {
    "pwd": "r1pper",
    "mail": "example@gmail.com"
  },
  "somenamerighthere": {
    "pwd": "hash",
    "mail": "email@email.net"
  }
}

Instead the javascipt takes the expression quite literall:

{
  "john": {
    "pwd": "r1pper",
    "mail": "example@gmail.com"
  },
  "name": {
    "pwd": "pwd",
    "mail": "mail"
  }
}

I'm quite new to javascript/json and would appreciate if you guys exlain to me how one could dynamically(!) generate json objects and feed them into a bigger data structure. None of the answers I found on SO could solve this problem in a way I could understand. Do I need to make changes to the datastructure, or have I just misunderstood the javascript/node.js syntax. Thanks in advance :)

Edit: I solved the problem quite simply. Turns out javascript actually passes the variables into the json and I was just confused:

{
  "john": {
    "pwd": "r1pper",
    "mail": "example@gmail.com"
  },
  "name": {
    "pwd": "hash",
    "mail": "email@email.net"
  }
}

Now we just need to pass the name dynamically, which can be solved by treating the JSON, as if it was an array:

database[name]

treats name as a variable.

Edit 2:

The comments below came in while editing. I apologize for that.

PixelRayn
  • 392
  • 2
  • 13

1 Answers1

0

you should use database[name] (take the value of name and use as index)

instead of database.name (use the string 'name' as index)

apple apple
  • 10,292
  • 2
  • 16
  • 36