简体   繁体   English

将子数组推入JavaScript数组

[英]Pushing Sub-array to JavaScript array

I'm trying to use JS to build a JSON array that looks very much like this: 我正在尝试使用JS构建看起来非常像这样的JSON数组:

{  
   "someKey":"someValue",
   "lines":{  
         "1": {
            "someKey": "someValue"
         },
         "2" {
            "someKey": "someValue"
         },
   }

}

Here's my JavaScript: 这是我的JavaScript:

var myArray = {
    someKey: "someValue",
    lines: []
};


var count = 0;  

$('.class_that_exists_twice').each(function() {

count ++;           

    myArray.lines[count] = {
    someKey: "someValue",
    };

});

However, the array that is returned looks wrong. 但是,返回的数组看起来错误。 Any ideas what I'm doing wrong? 有什么想法我做错了吗? (Please let me know if I should post the array as well) (请让我知道是否也应该发布数组)

Thank you very much! 非常感谢你!

What you are trying to create is not an array but an object. 您尝试创建的不是数组而是对象。 So it should be like this: 所以应该是这样的:

var myArray = {
  someKey: "someValue",
  lines: {}
};

The rest looks fine 其余的看起来不错

In the first JSON lines is an object. 在第一行JSON行中是一个对象。 If you want to get your JSON to look like that you could do this: 如果要使JSON看起来像这样,可以执行以下操作:

var myArray = {
    someKey: "someValue",
    lines: {}
};

$('.class_that_exists_twice').each(function(index, obj) {         
    myArray.lines[index] = {
        someKey: "someValue",
    };
});

Fiddle: http://jsfiddle.net/g1pseum6/ 小提琴: http : //jsfiddle.net/g1pseum6/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM