Mike Oltmans
Mike Oltmans

Reputation: 79

json object with nested objects

If you have the below:

var test = '{"0":"1", "2":"3"}';

if produces object 0: 1 2: 3

How do I create a object with like object: object: 0: 1 2: 3 object: 4: 5 6: 7

I have tried:

var test = '[{"0":"1", "2":"3"}]';

or

var test = '{"0": {"0":"1", "2":"3"}}';

Upvotes: 1

Views: 113

Answers (3)

Ma3x
Ma3x

Reputation: 6549

You are using strings instead of JSON. You can simply use {} to define objects and [] to define arrays and "key" : value syntax for key-value pairs.

var objA = { "0": "1", "2": "3" };
var objB = { "4": "5", "6": "7" };

var test = { "0": objA, "1": objB };

or in one line

var test = { "0": { "0": "1", "2": "3" }, "1": { "4": "5", "6": "7" } };

If you need to parse JSON strings then you can use

var test = JSON.parse('{ "0": { "0": "1", "2": "3" }, "1": { "4": "5", "6": "7" } }');

Upvotes: 2

Sushanth --
Sushanth --

Reputation: 55740

Just create an array. And push the object into an array.

var obj = {};
    obj["0"] = "1";
    obj["2"] = "3";

var wObj = {};
    wObj["0"] = obj;
console.log(wObj);

This is nested object example. Check Fiddle

2nd Example object inside an array

var obj = {};
    obj["0"] = "1";
    obj["2"] = "3";

var wObj = [];

wObj.push(obj);
console.log(wObj);

Array Fiddle

Upvotes: 3

Kirk Backus
Kirk Backus

Reputation: 4866

Like this

var test = '[{"0":"1", "2":"3"}, {"0":"3", "1":"2"}]'

{"0":"1", "2":"3"} Is your first object

{"0":"3", "1":"2"} Is your second

All encapsulated in one array.

Upvotes: 1

Related Questions