Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object insert issue in JavaScript array [duplicate]

I have a JavaScript array like below:

[
    {type: 'text', name: 'title', id: 'title', placeholder: 'Type here'},
    {type: 'textarea', name: 'description', id: 'description', placeholder: 'Type here'}
]

Now I want to inset {type: 'text', name: 'age', id: 'age', placeholder: 'Type here'} after first object. So my final result set will be looks like:

[
    {type: 'text', name: 'title', id: 'title', placeholder: 'Type here'},
    {type: 'text', name: 'age', id: 'age', placeholder: 'Type here'}
    {type: 'textarea', name: 'description', id: 'description', placeholder: 'Type here'}
]

I want in plain JavaScript or jQuery!

like image 419
Deepak Biswal Avatar asked Aug 08 '13 11:08

Deepak Biswal


2 Answers

like this:

var a = [
    {type: 'text', name: 'title', id: 'title', placeholder: 'Type here'},
    {type: 'textarea', name: 'description', id: 'description', placeholder: 'Type here'}
]

var b= {type: 'text', name: 'age', id: 'age', placeholder: 'Type here'} 

a.splice(1,0,b);

console.log(a)
like image 130
Manish Kumar Avatar answered Sep 18 '22 02:09

Manish Kumar


If your array is in variable array, then:

array.splice(1, 0, {
    type: 'text',
    name: 'age',
    id: 'age',
    placeholder: 'Type here'
});

The 1 means that you want to place it at index 1, 0 means you want to delete 0 items from the array. See splice documentation, it is quite the abomination of a method with 2 purposes of which both are never used at the same time :D

like image 41
Esailija Avatar answered Sep 22 '22 02:09

Esailija