6

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!

Deepak Biswal
  • 4,280
  • 2
  • 20
  • 37

3 Answers3

6

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)
Manish Kumar
  • 15,269
  • 5
  • 18
  • 27
5

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

Esailija
  • 138,174
  • 23
  • 272
  • 326
-1

If you want that object at that exact position, use the splice method.

var myArray = [{
  type: 'text',
  name: 'title',
  id: 'title',
  placeholder: 'Type here'
}, {
  type: 'textarea',
  name: 'description',
  id: 'description',
  placeholder: 'Type here'
}];
var myObject = {
  type: 'text',
  name: 'age',
  id: 'age',
  placeholder: 'Type here'
};
myArray.push(myObject);
Pang
  • 9,564
  • 146
  • 81
  • 122
T145
  • 69
  • 8