deepakb deepakb - 21 days ago 5
Javascript Question

Object insert issue in JavaScript array

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!

Answer

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)