CSK
CSK

Reputation: 777

insert Array of object into Last index using jquery

var a=[{"id":1, "name":"aaa", "age":31}, {"id":2, "name":"bbb", "age":23}, {"id":3, "name":"ccc", "age":24}]

var b=[{"id":4, "name":"ddd", "age":43}]

var result=[{"id":1, "name":"aaa", "age":31}, {"id":2, "name":"bbb", "age":23}, {"id":3, "name":"ccc", "age":24}, {"id":4, "name":"ddd", "age":43}]

I want to insert b into an index of 3. anybody know this one?

Upvotes: 0

Views: 118

Answers (6)

Vikram Singh
Vikram Singh

Reputation: 56

Please check below code

var a = [{ "id": 1, "name": "aaa", "age": 31 }, { "id": 2, "name": "bbb", "age": 23 }, { "id": 3, "name": "ccc", "age": 24}];
        var b = [{ "id": 4, name: "ddd", "age": 43}];
        var result = a.concat(b);

Upvotes: 0

Jakaria
Jakaria

Reputation: 161

Good practice is

a[a.length] = b;

Here a.length is 3 that means next(or last) index to insert the data.

Upvotes: 1

sameer
sameer

Reputation: 320

Please check with the below code.

var a=[{"id": 1, "name":"aaa","age":31},{"id": 2, "name":"bbb","age":23},{"id": 3,name:"ccc","age":24}]
var b=[{"id": 4, "name":"ddd","age":43}];
function insertInto(index, a, b){
    var x = a.splice(index);
    a = a.concat(b);
    a = a.concat(x);
    retrun a;
}
a = insertInto(2,a,b);

Upvotes: 0

Greg
Greg

Reputation: 3568

a.push.apply(a, b)

This will call the Array's push method with as many arguments as there are items on b, that is to say a.push(b[0], b[1], b[2], ...)

Plain JS, no jQuery needed :)

PS: Note this modifies a. If you don't want this, then you can first clone it with Array.slice :

var result = a.slice(); 
result.push.apply(this, b);

Upvotes: 1

sameer
sameer

Reputation: 320

Please check the below code

var result = a.concat(b);

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

var result = a;
result.push(b[0]);

Upvotes: 1

Related Questions