1

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"}}';
1
  • 1
    i don't understand what you want exaclty, your pseudo code doesn't help much and btw your test variable doesn't produce what you say it produces, it is a string, so what are you expecting? Commented Jul 24, 2013 at 21:50

3 Answers 3

3

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

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

3 Comments

Could you give an example
Can you build the same thing in a single string I am going to use JSON.parse to make the string in to a nested object set
Your string should be in the form of Array of objects [{"0":"1"}, {"2":"3"}];
2

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" } }');

1 Comment

This is a nice answer!
1

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.

8 Comments

here test is a string
But why are you wrapping it in quotes?
That worked!! I swear I tried that exact same setup must have had a syntax error in mine. Ill give you a green check in 6 minutes ><
@MikeOltmans could you provide a sample of what 'it works' because here doesn't make sense at all!...
@roasted: Well the array with 2 objects should work, but the question was misleading asking for JSON object with nested objects.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.