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

2
  • 3
    arrayToSubmit is an object, not a JSON object. Commented Feb 17, 2015 at 6: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] = {...}; Commented Feb 17, 2015 at 6:22

4 Answers 4

3

You can use bracket notation, like this

var arrayToSubmit = {};

arrayToSubmit[location] = {};
arrayToSubmit[location][type] = {
  'qty': qty,
  'assetNumber': assetNumber
};
Sign up to request clarification or add additional context in comments.

3 Comments

This worked, thank you. I didnt figure out bracket notation before as I missed the line arrayToSubmit[location] = {};.
@VaMoose: The question you linked to already explains the exact same thing: 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.
@FelixKling I used bracket notation, I just didnt figure out how to do it properly, I missed the {} when creating the variable.
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.

Comments

0

Consider this code:

arrayToSubmit = {};
obj = {};
obj[type] = {
            'qty' : qty,
            'assetNumber' : assetNumber
        };
arrayToSubmit[location] = obj;

Comments

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

1 Comment

I missed that! Changing it now. Thanks !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.