0

I have an object as show below:

var obj = {
"title":"dummyTitle",
"description":"dummyDescription",
"valid":"true"
}

to the above already declared object I want to add a key value pair which is something like:

var propertiesKey="property",  //key
var propertiesValue={          //value
"propertyA":"a",
"propertyB":"b"
}

so this can be achieved by doing

obj[propertiesKey]=propertiesValue

but that would append it at the last of my existing object. What if i want to append it after title key ?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Sakshi
  • 1,464
  • 2
  • 8
  • 15
  • 1
    To clarify, [there is no such thing as a JSON object](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). [JSON is different to objects](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation?r=SearchResults). – VLAZ Dec 01 '20 at 10:14
  • Why does the key need to be specifically after `title`? – Dane Brouwer Dec 01 '20 at 10:15
  • If order is important, why not use an array of keyvaluepairs (string, unknown/any) –  Dec 01 '20 at 10:16
  • 1
    Other than that, it's best if you don't rely on a particular order of the keys in an object. [There *is* a guaranteed order since ES6](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties) but it might not be what you expect. It's insertion order but integer keys are always sorted first and by value. Moreover, many operations can disturb that order and adding "at a specific place" is hard to maintain. – VLAZ Dec 01 '20 at 10:17
  • There is no way to reorder object properties inline or insert them at certain positions. The only way to do it is to recreate the object. Are you aware that object properties might or might necessarily be ordered in the first place? Also they handle numeric keys differently. – str Dec 01 '20 at 10:17

0 Answers0