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 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)
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
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