1

I have JSON data

var json = {"options": {
              "key1": "value2",
              "key2": "value2",
              "key3": "value3",
                }
            }

And I want to add one more key with value to it using JavaScript, but I want it to be on the top like this:

var json = {"options": {
              "new_key": "new_value",
              "key1": "value2",
              "key2": "value2",
              "key3": "value3",
                }
            }

How can I do it?

Shepard
  • 1,111
  • 5
  • 16
  • 32
  • 9
    Objects do not have order, http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – epascarello Nov 27 '13 at 14:38
  • I think this is a good question but I can't imagine any case where this order is relevant in any way. – Daniel W. Nov 27 '13 at 14:40
  • @DanFromGermany Perhaps the user wants to iterate through the object and print them in a specific order? This could be done by creating another array called `order` and refering to the keys. – h2ooooooo Nov 27 '13 at 14:50
  • FYI, your code is dealing directly with JavaScript objects. The notation used for creating JSON data is similar, but your `json` variable most certainly does not hold JSON data. – Blue Skies Nov 27 '13 at 14:53
  • ...and even as JSON (if you removed the `var json =` part), it wouldn't be valid because of the trailing comma. – Blue Skies Nov 27 '13 at 14:53

5 Answers5

4

Objects do not guarantee property order in JavaScript, but arrays do. If the order really matters and you are allowed to change your JSON structure, I'd suggest to use an array instead to organize your data.

var json = {
    "options": [
        {"key": "key1", "value": "value1"},
        {"key": "key2", "value": "value2"},
        {"key": "key3", "value": "value3"}
    ]
};

Using this, you could push an element to the start of the array using the unshift method.

json.options.unshift({"key": "new_key", "value": "new_value"});
Guilherme Sehn
  • 6,727
  • 18
  • 35
3

Although it is not required by any of the ECMAScript specs, nonetheless most implementations do retain the original order of keys in Objects, with the exception of keys with numeric values. You can see a lengthy discussion about the Chrome's implementation here: http://code.google.com/p/v8/issues/detail?id=164

If you want to utilize this, you will need to create a new Object:

var newOpts = {};
newOpts["new_key"] = "new_value";
for (var k in json.options) {
    newOpts[k] = json.options[k];
}
json.options = newOpts;

However if you do actually turn your object into a JSON string, and send it to someone else, there is no guarantee that they will preserve the order when they parse the string back into an Object.

I was surprised to discover the widely used Express library for NodeJS actually relies on this behaviour for its format method.

joeytwiddle
  • 29,306
  • 13
  • 121
  • 110
1

JSON Objects have no order. If order is important to you, consideer creating options as an array, then you can iterate and adding items in a specific order:

var json = {"options": [
              {key: "new_key", value: "new_value"},
              {key: "key1", value: "value2"},
              {key: "key2", value: "value2"},
              {key: "key3", value: "value3"},
            ]}
Jorgeblom
  • 3,330
  • 1
  • 23
  • 24
1

You can extend the object in the following way using vanilla JavaScript but again this won't set the order as others have noted.

extend = function(destination, source) {   
    for (var property in source) {
        destination[property] = source[property];
    }
    return destination;
};

var json = {
    "options": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    }
};

extend(json.options, {"new_key": "new_value"});
Jonathan
  • 1,833
  • 13
  • 15
0

You could use the extend function the ordering of the objects would determine which parameters would be written first, but as stated by DanFromGermany there aren't many real-life cases where the order is relevant.

talegna
  • 2,407
  • 2
  • 19
  • 22
  • Objects are unordered, and JavaScript doesn't have an `extend` function. – Blue Skies Nov 27 '13 at 14:50
  • no the extend function is part of jQuery which is linked to on my response. It's a useful javascript library which includes functionality like that required by your problem. – talegna Nov 27 '13 at 14:52
  • Your answer is still wrong, because JavaScript objects are unordered. I've no idea why someone upvoted it. And there's no mention of jQuery in the question. It would be silly to include it just to extend an object. – Blue Skies Nov 27 '13 at 14:55
  • 3
    btw => http://meta.stackexchange.com/questions/45176/when-is-use-jquery-not-a-valid-answer-to-a-javascript-question – Guilherme Sehn Nov 27 '13 at 14:58