简体   繁体   中英

use variables as keys in multi level json object

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

You can use bracket notation , like this

var arrayToSubmit = {};

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

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.

Consider this code:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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