user45097
user45097

Reputation: 621

Building complex JSON in Javascript

Just started using JavaScript and need some guidance on how best to create /build the JSON below on the fly/dynamically.

Some of the keys will need to be from variables. For example in the JSON below, keys called 'variable_key_*' will need to be from a variable.

{
  "static_key_1": "value",
  "static_key_2": [{
    "static_key_3": {
      "id": "1097274153"
    },
    "static_key_4": "value",
    "static_key_5": {
      "static_key_6": {
        "variable_key_1": "value",
        "variable_key_2": "value",
        "variable_key_3": "value"
      },
      "static_key_7": {
        "static_key_8": [
          "value"
        ]
      }
    }
  }]
}

Upvotes: 0

Views: 2334

Answers (2)

Tim Consolazio
Tim Consolazio

Reputation: 4888

You can set keys in an object with variables by using bracket notation.

let theVariable = 'useful_name';
let theValue = 12345;
let myObj = {};

myObj [ theVariable ] = theValue;

Will result in:

{ useful_name : 12345 }

And stringify as you'd expect.

Edit based on request for more info:

Say you wanted to create a nested object with an array of objects, we'll use the object we already have.

myObj [ someOtherVar ] = {};
let myObjSomeOtherVar = myObj [ someOtherVar ];
myObjSomeOtherVar [ someOtherKey ] = [ ].push ( { } );
let theArrayOfObjects = myObjSomeOtherVar [ someOtherKey ];
theArrayOfObjects [ 0 ] [ anotherKeyName ] = 'hello';

This would result in (provided you actually declared all the vars etc)

{ useful_name : 12345,
  valOfSomeOtherVar : 
      { valOfSomeOtherKey : 
          [ { valOfAnotherKeyName : 'hello' } ] 
      }
} 

The trick is to just develop your data schema abstractly (so the skeleton you want), then write a routine that builds it. I rarely build an object by hand this way unless it's just a small util obj, I usually feed an empty object into a routine to build it out (using loops, recursion, conditionals, whatever). And as for practice, it is always a good idea to have a skeleton at least documented for a data structure, which can also be used as reference to write the function that can generate the whole thing just by passing it some variables for keynames and values. You would write a test for that function that would give you back the objects you'd predict, etc.

Upvotes: 2

ValLeNain
ValLeNain

Reputation: 2304

If you don't need to create it in one statement (and there is few chance you do), you'd do as follow:

var yourObject = {
  "static_key_1": "value",
  "static_key_2": [{
    "static_key_3": {
        "id": "1097274153"
    },
    "static_key_4": "value",
    "static_key_5": {
        "static_key_6": {},
        "static_key_7": {
            "static_key_8": [
                "value"
            ]
         }
     }
  }]
}

/* Get their value from wherever you want */
var variable_key_1 = 'something';
var variable_key_2 = 'something_else';
var variable_key_3 = 'another_one';

yourObject.static_key_2[0].static_key_5.static_key_6[variable_key_1] = 'value';
yourObject.static_key_2[0].static_key_5.static_key_6[variable_key_2] = 'value';
yourObject.static_key_2[0].static_key_5.static_key_6[variable_key_3] = 'value';

The strategy is to build the objects with properties with variables names after the ones with static names, using the brackets notation.

This will result in:

{
  "static_key_1": "value",
  "static_key_2": [{
    "static_key_3": {
        "id": "1097274153"
    },
    "static_key_4": "value",
    "static_key_5": {
        "static_key_6": {
          "something": "value",
          "something_else": "value",
          "another_one": "value"
        },
        "static_key_7": {
            "static_key_8": [
                "value"
            ]
         }
     }
  }]
}

Upvotes: 1

Related Questions