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!

2
  • 2
    Kindly post your attempt(s). Commented Aug 8, 2013 at 11:47
  • I have tried with push but it always add at the end! Commented Aug 8, 2013 at 11:47

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This would actually have to be a.splice(1,0,b)
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

Comments

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

2 Comments

this will add the required object at the last of the array.
Did you read my edit? Please don't be so forthcoming.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.