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"}}';
-
1i 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?A. Wolff– A. Wolff2013年07月24日 21:50:04 +00:00Commented Jul 24, 2013 at 21:50
3 Answers 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);
-
1Could you give an exampleMike Oltmans– Mike Oltmans2013年07月24日 21:46:56 +00:00Commented Jul 24, 2013 at 21:46
-
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 setMike Oltmans– Mike Oltmans2013年07月24日 21:50:30 +00:00Commented Jul 24, 2013 at 21:50
-
Your string should be in the form of Array of objects
[{"0":"1"}, {"2":"3"}];
Sushanth --– Sushanth --2013年07月24日 21:52:19 +00:00Commented Jul 24, 2013 at 21:52
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" } }');
-
This is a nice answer!A. Wolff– A. Wolff2013年07月24日 22:00:21 +00:00Commented Jul 24, 2013 at 22:00
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.
-
here test is a stringA. Wolff– A. Wolff2013年07月24日 21:47:51 +00:00Commented Jul 24, 2013 at 21:47
-
But why are you wrapping it in quotes?A. Wolff– A. Wolff2013年07月24日 21:52:19 +00:00Commented Jul 24, 2013 at 21:52
-
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 ><Mike Oltmans– Mike Oltmans2013年07月24日 21:52:31 +00:00Commented Jul 24, 2013 at 21:52
-
@MikeOltmans could you provide a sample of what 'it works' because here doesn't make sense at all!...A. Wolff– A. Wolff2013年07月24日 21:53:43 +00:00Commented Jul 24, 2013 at 21:53
-
@roasted: Well the array with 2 objects should work, but the question was misleading asking for JSON object with nested objects.Ma3x– Ma3x2013年07月24日 22:02:05 +00:00Commented Jul 24, 2013 at 22:02