最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

adding to javascript multi-dimensional array - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 4
  1. To 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 the i variable.

  2. 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++;
}
发布评论

评论列表(0)

  1. 暂无评论