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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With