0

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"
        ]
      }
    }
  }]
}
5
  • Your question isn't clear, and isn't specific enough. Please edit to rectify that. Commented Feb 14, 2017 at 21:06
  • 1
    your JS object is malformed, the value you affect to "static_key_2" is a mix of an object and an array. First verify your object with a tool like jsonlint.com and then edit your post (the tool works because in your case, the JS object will be directly mapped to a JSON object) :) Commented Feb 14, 2017 at 21:09
  • @isherwood I've attempted to make it clearer. Commented Feb 14, 2017 at 21:16
  • @valLeNain I'll take a look at JSONLint. Thx Commented Feb 14, 2017 at 21:16
  • @valLeNain I've checked in JSONLint and fixed errors and reposted. Commented Feb 14, 2017 at 21:22

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi @Tim Consolazio, thanks for the feedback. I understand your post. But how would I go about creating the nested parts of the JSON? Say from static_key_2 onwards?
I'd probably write a routine that lets me feed in the info and generates the entire object. I'll post a little sample that shows how to create a single nested array.
Hi @Tim Consolazio, just giving this a go now. I've copied and declared vars (changed let to vars as node was complaining) and getting this error: TypeError: Cannot set property 'anotherKeyName' of undefined - theArrayOfObjects [ 0 ] [ anotherKeyName ] = 'hello';.
Did you make sure to push an object onto the array? I'd wager there's no object at theArray [ 0 ]
Thanks for the guidance!
1

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"
            ]
         }
     }
  }]
}

2 Comments

Hi @vallenain, Thanks for the feedback. I've run the above via Node cmd line. When I console.out(yourObject) sometthing isn't right as it only shows the following { static_key_1: 'value', static_key_2: [ { static_key_3: [Object], static_key_4: 'value', static_key_5: [Object] } ] }
that's just the way it's printed. The object itself should be as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.