0

I have a JSON object called arrayToSubmit. Here is the following code:

location = "Johannesburg, South Africa";
type = "bench";
qty = 1;
assetNumber = 15;

arrayToSubmit = {
    location : {
        type : {
            'qty' : qty,
            'assetNumber' : assetNumber
        }
    }
}

But the result in chrome is as follows:

Object{location { type : {"qty" : "1", "assetNumber" : "15"}}}

I need to replace the words location and type with the variables in the initial code, like this:

Object{"Johannesburg, South Africa" = { "bench" = {"qty" - "1", "assetNumber" : "15"}}}

(I am pulling these values from my page, I just typed them out here for ease of use).

I have already tried these two examples, but don't know how to get it in multi level format.

is a way that use var to create json object in key

how to set a json key from a variable

Community
  • 1
  • 1
VaMoose
  • 196
  • 7
  • 3
    arrayToSubmit is an object, not a JSON object. –  Feb 17 '15 at 06:16
  • 1
    I guess you couldn't figure out how to refer to the "location" property after setting it? Like so: `var data = {}; data[location] = {}; data[location][type] = {...};` – Felix Kling Feb 17 '15 at 06:22

4 Answers4

3

You can use bracket notation, like this

var arrayToSubmit = {};

arrayToSubmit[location] = {};
arrayToSubmit[location][type] = {
  'qty': qty,
  'assetNumber': assetNumber
};
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
  • This worked, thank you. I didnt figure out bracket notation before as I missed the line `arrayToSubmit[location] = {};`. – VaMoose Feb 17 '15 at 06:34
  • 1
    @VaMoose: The question you linked to already explains the exact same thing: http://stackoverflow.com/a/882749/218196. Using bracket notation is the solution, how could you have missed that? *edit:* Or did you mean you forgot to create the object? I mean, you cannot just do `var foo; foo[bar] = '...';` either, you have to create the object first. – Felix Kling Feb 17 '15 at 06:36
  • @FelixKling I used bracket notation, I just didnt figure out how to do it **properly**, I missed the `{}` when creating the variable. – VaMoose Feb 17 '15 at 06:42
1

You have to use the [] operator to use a variable value as a key. When declaring properties inside the object initializer {} the keys are always literal.

You do it like this :

var location = "Johannesburg, South Africa";
var objectToSubmit = {};
objectToSubmit[location] = {...};

Hope this helps.

G Roy
  • 166
  • 3
0

Consider this code:

arrayToSubmit = {};
obj = {};
obj[type] = {
            'qty' : qty,
            'assetNumber' : assetNumber
        };
arrayToSubmit[location] = obj;
Manwal
  • 23,450
  • 12
  • 63
  • 93
0

First of all, do not use 'location', it will interfere with window.location variable.

arrayToSubmit = {};
arrayToSubmit[loc] = {};
arrayToSubmit[loc][type] = {
    'qty' : qty,
    'assetNumber' : assetNumber
};
Evgeniy
  • 2,915
  • 3
  • 21
  • 35