I want the following structure:
{
"1":[
{"name":"John","Age":"21"}
]
"2":[
{"name":"Jone","Age":"22"}
]
}
I want to dynamically add objects.This is what I tried:
var i = 0;
var data= [{i:{}}];
function add(){
data= [{i:{}}];
data.i.push({
"name":"Zack",
"age":22
});
i++;
}
I got an error "Cannot call method 'push' of undefined"
I want the following structure:
{
"1":[
{"name":"John","Age":"21"}
]
"2":[
{"name":"Jone","Age":"22"}
]
}
I want to dynamically add objects.This is what I tried:
var i = 0;
var data= [{i:{}}];
function add(){
data= [{i:{}}];
data.i.push({
"name":"Zack",
"age":22
});
i++;
}
I got an error "Cannot call method 'push' of undefined"
Share Improve this question asked Jun 27, 2013 at 7:00 phpcoderxphpcoderx 5705 silver badges16 bronze badges3 Answers
Reset to default 4To access a property dynamically, use the bracket notation.
data= [{i:{}}]
doesn't do what you want, it doesn't use the fact you just defined thei
variable.In your function, you're replacing the external value of
data
.
What you want is probably much simpler :
var i = 0;
var data= {};
function add(){
data[i] = data[i]||[];
data[i].push({
"name":"Zack",
"age":22
});
i++;
}
More details in this MDN documentation : Working with objects
By declaring data
as [{i:{}}]
, the structure you are obtaining is actually
[
{
i: {
}
}
]
Which is not the one you wanted, and the reason why you can't access data.i
(since data
is an array).
You should declare data
as {i:{}}
and then access i
with the bracket notation, as data[i]
.
Besides, since data[i]
is not an array, .push
won't work either, so you should use something like data[i] = {"name": "Raibaz", "age": 30}
.
In Javascript multi dimensional arrays are created by using following syntax
var mArray = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
and
mArray[0][0] gives 1
mArray[0][1] gives 2
mArray[1][0] gives 3
mArray[1][1] gives 4
You can initialize your multidimensional array as given below
var i = 0;
var data= [];
What you are trying to create is an object of arrays. In that case syntax is (as in your code)
var mObject = {
"1":[
{"name":"John","Age":"21"}
]
"2":[
{"name":"Jone","Age":"22"}
]
};
You can initialize your object as given below
var i = 1;
var data= {};
And in both cases the function can be written as given below
function add(){
data[i] = data[i] || []; // initializes array if it is undefined
data[i].push({
"name":"Zack",
"age":22
});
i++;
}