jquery - Javascript array within JSON Object - Stack Overflow

I'm trying to achieve this structure (a JSON Object with an array inside):var data = {page : '

I'm trying to achieve this structure (a JSON Object with an array inside):

var data = {
     page : 'hello',
     rows: [
          {
              column: 'two'
          }
     ] 
}

But i'm failing miserable, trying various methods, this is my work in progress code:

var data = new Array();
    data['settings'] = [];
    var i = 0;
    var inputName, value;
    for (i; i < inputs.length; i++){
        inputName = $(inputs[i]).attr('name');
        value = $(inputs[i]).val();
        data['settings'][inputName] = value;
    }
    data['page_id'] = page_id;

So i know the variable names are not the same as the desired example but you get the general gist! At the moment, its just making data an empty array. But i need to make it a JSON object with the idea to send it to a server.

I'm trying to achieve this structure (a JSON Object with an array inside):

var data = {
     page : 'hello',
     rows: [
          {
              column: 'two'
          }
     ] 
}

But i'm failing miserable, trying various methods, this is my work in progress code:

var data = new Array();
    data['settings'] = [];
    var i = 0;
    var inputName, value;
    for (i; i < inputs.length; i++){
        inputName = $(inputs[i]).attr('name');
        value = $(inputs[i]).val();
        data['settings'][inputName] = value;
    }
    data['page_id'] = page_id;

So i know the variable names are not the same as the desired example but you get the general gist! At the moment, its just making data an empty array. But i need to make it a JSON object with the idea to send it to a server.

Share Improve this question asked Jan 25, 2012 at 10:59 benhowdle89benhowdle89 37.5k74 gold badges207 silver badges340 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

What you've quoted is a JavaScript object with a JavaScript array in it, no JSON* in sight.

To create it, I don't think you want an array at all, just an object with a nested object:

var data = {
    settings: {},
    page_id:  page_id
};
var i, input;
for (i = 0; i < inputs.length; i++){
    input = $(inputs[i]);
    data.settings[input.attr('name')] = input.val();
}

That works because JavaScript objects are maps of name/value pairs. You can refer to a property of an object using dotted notation and a literal property name:

x = obj.foo;

...or using bracketed notation and a string name:

x = obj["foo"];

In the latter case, you can use any expression you like for the string, so for instance:

x = obj["f" + "o" + "o"];

JavaScript also has literal object initializers, which you can use to create an object with properties already on it:

obj = {foo: "bar"};

That creates an object with a property called foo with the value "bar" and assigns the object to the obj variable.

So looking again at the code block above:

  1. We create an object with the properties settings and page_id. settings is initialized with a blank object; page_id is initialized with the value of the page_id variable.

  2. Then we loop through your inputs and add properties to settings using the name of each input, setting the value of the property to be the value of the input.

So let's assume we have

<input name="oneField" value="bar">
<input name="anotherField" value="bang">
<input name="yetAnotherField" value="cool">

...and let's assume page_id is 3.

We'll end up with this structure in the object referenced by the data variable:

{
    settings: {
        oneField: "bar",
        anotherField: "bang",
        yetAnotherField: "cool"
    },
    page_id:  page_id
}

* JSON is a textual notation. When you're writing things like var data = { ... }; in code, you're just using JavaScript. JSON is a subset of JavaScript literal syntax that's designed to be easy to parse, so for instance it's handy for storing arbitrary plex data in data stores, or for retrieving data from a server. You retrieve the string, which contains the data, and then parse that string to build up an object structure in memory.

var data = {};
data['settings'] = {};
var i = 0;
var inputName, value;
for (i; i < inputs.length; i++){
    inputName = $(inputs[i]).attr('name');
    value = $(inputs[i]).val();
    data['settings'][inputName] = value;
}
data['page_id'] = page_id;

This will give you such result like below:

{
     page_id: 12345,
     setting: { foo: 'one', bar: 'two'}
}

Both [] and new Array() are used to initialize an array; what you're after (as you're trying to map keys to values), are objects; which are initialized using either {} or new Object().

var data = {};
    data['settings'] = {};
    var i = 0;
    var inputName, value;
    for (i; i < inputs.length; i++){
        inputName = $(inputs[i]).attr('name');
        value = $(inputs[i]).val();
        data['settings'][inputName] = value;
    }
    data['page_id'] = page_id;

To help you with your syntax, square bracket notation is only needed if the member you're looking up is a variable, or if the key contains reserved words or special characters (spaces etc). Otherwise, you can use dot notation;

var data = {};
    data.settings = {};
    var i = 0;
    var inputName, value;
    for (i; i < inputs.length; i++){
        inputName = $(inputs[i]).attr('name');
        value = $(inputs[i]).val();
        data.settings[inputName] = value;
    }
    data.page_id = page_id;

When using object literal syntax ({}) to construct an object, you are allowed to define members on the object as well. It's also more mon to declare your looping variable within the for loop rather than outside.

var data = {
        settings: {}
    };
    var inputName, value;
    for (var i=0; i < inputs.length; i++){
        inputName = $(inputs[i]).attr('name');
        value = $(inputs[i]).val();
        data.settings[inputName] = value;
    }
    data.page_id = page_id;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745361291a4624372.html

相关推荐

  • jquery - Javascript array within JSON Object - Stack Overflow

    I'm trying to achieve this structure (a JSON Object with an array inside):var data = {page : '

    4小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信