Dan Hodson
Dan Hodson

Reputation: 309

Adding to JS objects in awkward places

If I have something like the following JS object as an example:

self.JSON = {
    "key1": ["1", "2", "paul"],
    "key2": true,
    "key3": {
         "key3.1": true,
         "key3.2": ["yes", "no", "maybe"]
    "key4": false,
    "key5": ["10", "9", "17", "4"]
    }
}

How could I use Javascript to put the following:

"newKey": {
    "newKey1": true,
    "newKey2": ["yes", "no", "maybe"]
},

Into this object between two keys, for example, between "key2" & "key3" whilst still maintaining the existing structure so that the final object would look like this:

self.JSON = {
    "key1": ["1", "2", "paul"],
    "key2": true,
    "newKey": {
        "newKey1": true,
        "newKey2": ["yes", "no", "maybe"]
    },
    "key3": {
         "key3.1": true,
         "key3.2": ["yes", "no", "maybe"]
    "key4": false,
    "key5": ["10", "9", "17", "4"]
    }
}

Upvotes: 1

Views: 45

Answers (1)

millerbr
millerbr

Reputation: 2961

Javascript objects are unordered. You can't control where to place the keys.

As specified in the spec: http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf

Upvotes: 3

Related Questions