I’m trying to store objects in an array using JavaScript, but I’m not sure what’s going wrong with my code. Here’s what I have:
function() {
var a = new array();
var b = new object();
a[0] = b;
}
I want to know how to properly javascript add object to array, so I can store many objects in the array and use them later in different functions. What’s the best way to add an object to an array in JavaScript, and how can I save it to a variable?
You know, after working with JavaScript for a while, the go-to method I always use is .push()
. It’s simple, effective, and does the job:
let myArray = [];
let myObject = { name: "Alice", age: 30 };
myArray.push(myObject);
This is probably the most common and straightforward way to javascript add object to array. The push()
method just appends your object to the end of the array. No complications, and you’re all set.
That’s a great point, @joe-elmoufak If you’re starting fresh with an array and an object, sometimes I find it cleaner to add them directly together from the start, like this:
let myArray = [{ name: "Bob", age: 25 }];
Or dynamically, if the object comes in later:
let obj = { id: 1, title: "Book" };
let arr = [obj];
This is a simple, compact way to javascript add object to array right from the get-go. It eliminates the need for separate steps and keeps things neat.
Nice, @raimavaswani And if you want to go a different route, maybe inserting an object at the beginning of the array instead of the end? You can use .unshift()
:
let items = [];
let item = { product: "Pen", price: 2 };
items.unshift(item);
This is especially useful if you want to have the newest objects appear first in the list. It’s still a very readable and effective way to javascript add object to array. Plus, it gives you a bit more control over where your objects land in the array.