7

Possible Duplicate:
Does JavaScript Guarantee Object Property Order?

I would like to know how I can insert a JSON object property at a specific position? Let's assume this Javascript object:

var data = {
  0: 'lorem',
  1: 'dolor sit',
  2: 'consectetuer'
}

I have an ID and a string, like:

var id = 6;
var str = 'adipiscing';

Now, I would like to insert the id between 0 and 1 (for example) and it should be like:

data = {
  0: 'lorem',
  6: 'adipiscing',
  1: 'dolor sit',
  2: 'consectetuer'
}

How can I do this? Is there any jQuery solution for this?

Community
  • 1
  • 1
Chris X
  • 891
  • 3
  • 9
  • 19

1 Answers1

9

To specify an order in which elements of an object are placed, you'll need to use an array of objects, like this:

data = [
    {0: 'lorem'},
    {1: 'dolor sit'},
    {2: 'consectetuer'}
]

You can then push a element to a certain position in the array:

// Push {6: 'adipiscing'} to position 1
data.splice(1, 0, {6: 'adipiscing'})

// Result:
data = [
    {0: 'lorem'},
    {6: 'adipiscing'},
    {1: 'dolor sit'},
    {2: 'consectetuer'}
]
// Access it:
data[0][0] //"lorem"

However, this will render the indices you've specified ({0:) pretty much useless.

Cerbrus
  • 60,471
  • 15
  • 115
  • 132
  • 1
    The problem is that here you used an array instead of the object – gildniy Jan 12 '20 at 19:40
  • The problem is that objects in JavaScript don't support ordered iteration, the OP's data structure is weird, and this question is from ***2012***. It's hella' old! – Cerbrus Jan 26 '21 at 08:20