How to insert object into array without push?

Forums JavaScriptHow to insert object into array without push?
Staff asked 3 years ago

Answers (3)

Add Answer
Staff answered 3 years ago
Using splice function,

var arr = [{id:1,name:"rajvir"},{id:3,name:"raj"}];
var obj = {id:5,name:"dhvani"}

arr.splice(2, 0, obj); //(index,how many?,Object)
console.log(arr);
//Output arr = [{id:1,name:"rajvir"},{id:3,name:"raj"},{id:5,name:"dhvani"}];
Staff answered 3 years ago

Try this solution

Example:

let Fruits =['Banana'];
let moreFruits = ['Orange','Mango'];
Fruits = [...Fruits ,...moreFruits ];
console.log(Fruits.join(','));
//final array Fruits output
//{'Banana','Orange','Mango'}

 

Staff answered 3 years ago

Try this solution

var zoo=[{animal:'dog'},{animal:'cat'}];
var obj={animal:'horse'};
var data=zoo.splice(zoo.length,0,obj);
console.log(zoo);

 

Subscribe

Select Categories