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?
-
You should check this:- api.jquery.com/appendRahul Tripathi– Rahul Tripathi2014年09月03日 07:12:01 +00:00Commented Sep 3, 2014 at 7:12
6 Answers 6
var result = a;
result.push(b[0]);
Sign up to request clarification or add additional context in comments.
2 Comments
Greg
good call, though it only works when there is only 1 item in b
Bhojendra Rauniyar
Yeah you can use apply() or call() method but OP hasn't mentioned that so I just answered that...
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);
answered Sep 3, 2014 at 7:18
Greg
3,5983 gold badges21 silver badges20 bronze badges
Comments
Good practice is
a[a.length] = b;
Here a.length is 3 that means next(or last) index to insert the data.
Comments
Please check the below code
var result = a.concat(b);
3 Comments
Greg
this won't produce the result the PR expects, he'll have an array as the last item in a instead (b being an array)
sameer
@Greg Concat function will concat two arrays and create a new array
Greg
Actually you're right @sameer, if the goal is not to modify
a this is a good answer.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);
Comments
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);
Romano Zumbé
8,1495 gold badges37 silver badges61 bronze badges
Comments
lang-js