benhowdle89
benhowdle89

Reputation: 37464

Javascript array within JSON Object

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.

Upvotes: 3

Views: 6856

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074295

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 complex 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.

Upvotes: 3

Matt
Matt

Reputation: 75317

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 common 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;

Upvotes: 0

xdazz
xdazz

Reputation: 160833

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'}
}

Upvotes: 0

Related Questions