How to push the values into array with key name using node.js to construct a json


I have a node js code with variables:
var elements = []; var subelement1 = {}; var subelement2 = {};

How to construct the json with the structure as following:

     "subelement1" :{},
     "subelement2" :{}  
Problem courtesy of: Prem


To combine them, set each "sub" object to a property of the main:

elements.subelement1 = subelement1;
elements.subelement2 = subelement2;

Then, you can stringify them with the surrounding object:

var json = JSON.stringify({ elements: elements });

Though, with named keys, you'll want to use an Object.

var elements = {};
    "elements": {
        "subelement1": {},
        "subelement2": {}

While Arrays can have named properties, they can't be given within a literal.

var foo = []; = 'baz';

And won't be acknowledged/counted like numeric indexes.

console.log(;    // "baz"
console.log(foo.length); // 0

foo[0] = 'qux';
console.log(foo.length); // 1
Solution courtesy of: Jonathan Lonowski


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.