- JavaScript Array of Objects Tutorial – How to Create, Update, and Loop Through Objects Using JS Array Methods
- Creating an array of objects
- Add a new object at the start — Array.unshift
- Add a new object at the end — Array.push
- Add a new object in the middle — Array.splice
- Looping through an array of objects
- Find an object in an array by its values — Array.find
- Get multiple items from an array that match a condition — Array.filter
- Transform objects of an array — Array.map
- Add a property to every object of an array — Array.forEach
- Sort an array by a property — Array.sort
- Checking if objects in array fulfill a condition — Array.every, Array.includes
- Summary
- Object.values()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Using Object.values()
- Using Object.values() on primitives
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Object.values()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Using Object.values()
- Using Object.values() on primitives
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Object.entries()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Using Object.entries()
- Using Object.entries() on primitives
- Converting an Object to a Map
- Iterating through an Object
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
JavaScript Array of Objects Tutorial – How to Create, Update, and Loop Through Objects Using JS Array Methods
Ondrej Polesny
On average I work with JSON data 18 times a week. And I still need to google for specific ways to manipulate them almost every time. What if there was an ultimate guide that could always give you the answer?
In this article, I’ll show you the basics of working with object arrays in JavaScript.
If you ever worked with a JSON structure, you’ve worked with JavaScript objects. Quite literally. JSON stands for JavaScript Object Notation.
Creating an object is as simple as this:
This object represents a car. There can be many types and colors of cars, each object then represents a specific car.
Now, most of the time you get data like this from an external service. But sometimes you need to create objects and their arrays manually. Like I did when I was creating this e-shop:
Considering each category list item looks like this in HTML:
I didn’t want to have this code repeated 12 times, which would make it unmaintainable.
Creating an array of objects
But let’s get back to cars. Let’s take a look at this set of cars:
We can represent it as an array this way:
Arrays of objects don’t stay the same all the time. We almost always need to manipulate them. So let’s take a look at how we can add objects to an already existing array.
Add a new object at the start — Array.unshift
To add an object at the first position, use Array.unshift .
Add a new object at the end — Array.push
To add an object at the last position, use Array.push .
Add a new object in the middle — Array.splice
To add an object in the middle, use Array.splice . This function is very handy as it can also remove items. Watch out for its parameters:
So if we want to add the red Volkswagen Cabrio on the fifth position, we’d use:
let car = < "color": "red", "type": "cabrio", "registration": new Date('2016-05-02'), "capacity": 2 >cars.splice(4, 0, car);
Looping through an array of objects
Let me ask you a question here: Why do you want to loop through an array of objects? The reason I’m asking is that the looping is almost never the primary cause of what we want to achieve.
JavaScript provides many functions that can solve your problem without actually implementing the logic in a general cycle. Let’s take a look.
Find an object in an array by its values — Array.find
Let’s say we want to find a car that is red. We can use the function Array.find .
let car = cars.find(car => car.color === "red");
This function returns the first matching element:
It’s also possible to search for multiple values:
let car = cars.find(car => car.color === «red» && car.type === «cabrio»);
In that case we’ll get the last car in the list.
Get multiple items from an array that match a condition — Array.filter
The Array.find function returns only one object. If we want to get all red cars, we need to use Array.filter .
let redCars = cars.filter(car => car.color === "red"); console.log(redCars); // output: // [ // < // color: 'red', // type: 'station wagon', // registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)', // capacity: 5 // >, // < // color: 'red', // type: 'cabrio', // registration: 'Sat Mar 03 2012 01:00:00 GMT+0100 (GMT+01:00)', // capacity: 2 // >// ]
Transform objects of an array — Array.map
This is something we need very often. Transform an array of objects into an array of different objects. That’s a job for Array.map . Let’s say we want to classify our cars into three groups based on their size.
let sizes = cars.map(car => < if (car.capacity if (car.capacity return "large"; >); console.log(sizes); // output: // ['large','medium','medium', . 'small']
It’s also possible to create a new object if we need more values:
let carsProperties = cars.map(car => < let properties = < "capacity": car.capacity, "size": "large" >; if (car.capacity if (car.capacity return properties; >); console.log(carsProperties); // output: // [ // < capacity: 7, size: 'large' >, // < capacity: 5, size: 'medium' >, // < capacity: 5, size: 'medium' >, // < capacity: 2, size: 'small' >, // . // ]
Add a property to every object of an array — Array.forEach
But what if we want the car size too? In that case we can enhance the object for a new property size . This is a good use-case for the Array.forEach function.
cars.forEach(car => < car['size'] = "large"; if (car.capacity if (car.capacity >);
Sort an array by a property — Array.sort
When we’re done with transforming the objects, we usually need to sort them one way or another.
Typically, the sorting is based on a value of a property every object has. We can use the Array.sort function, but we need to provide a function that defines the sorting mechanism.
Let’s say we want to sort the cars based on their capacity in descending order.
let sortedCars = cars.sort((c1, c2) => (c1.capacity < c2.capacity) ? 1 : (c1.capacity >c2.capacity) ? -1 : 0); console.log(sortedCars); // output: // [ // < // color: 'purple', // type: 'minivan', // registration: 'Wed Feb 01 2017 00:00:00 GMT+0100 (GMT+01:00)', // capacity: 7 // >, // < // color: 'red', // type: 'station wagon', // registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)', // capacity: 5 // >, // . // ]
The Array.sort compares two objects and puts the first object in the second place if the result of the sorting function is positive. So you can look at the sorting function as if it was a question: Should the first object be placed in second place?
Make sure to always add the case for zero when the compared value of both objects is the same to avoid unnecessary swaps.
Checking if objects in array fulfill a condition — Array.every, Array.includes
Array.every and Array.some come handy when we just need to check each object for a specific condition.
Do we have a red cabrio in the list of cars? Are all cars capable of transporting at least 4 people? Or more web-centric: Is there a specific product in the shopping cart?
cars.some(car => car.color === "red" && car.type === "cabrio"); // output: true cars.every(car => car.capacity >= 4); // output: false
You may remember the function Array.includes which is similar to Array.some , but works only for primitive types.
Summary
In this article, we went through the basic functions that help you create, manipulate, transform, and loop through arrays of objects. They should cover most cases you will stumble upon.
If you have a use-case that requires more advanced functionality, take a look at this detailed guide to arrays or visit the W3 schools reference.
Or get in touch with me and I will prepare another article 🙂
Object.values()
The Object.values() static method returns an array of a given object’s own enumerable string-keyed property values.
Try it
Syntax
Parameters
Return value
An array containing the given object’s own enumerable string-keyed property values.
Description
Object.values() returns an array whose elements are values of enumerable string-keyed properties found directly upon object . This is the same as iterating with a for. in loop, except that a for. in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.values() is the same as that provided by a for. in loop.
If you need the property keys, use Object.keys() instead. If you need both the property keys and values, use Object.entries() instead.
Examples
Using Object.values()
const obj = foo: "bar", baz: 42 >; console.log(Object.values(obj)); // ['bar', 42] // Array-like object const arrayLikeObj1 = 0: "a", 1: "b", 2: "c" >; console.log(Object.values(arrayLikeObj1)); // ['a', 'b', 'c'] // Array-like object with random key ordering // When using numeric keys, the values are returned in the keys' numerical order const arrayLikeObj2 = 100: "a", 2: "b", 7: "c" >; console.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a'] // getFoo is a non-enumerable property const myObj = Object.create( >, getFoo: value() return this.foo; >, >, >, ); myObj.foo = "bar"; console.log(Object.values(myObj)); // ['bar']
Using Object.values() on primitives
Non-object arguments are coerced to objects. Only strings may have own enumerable properties, while all other primitives return an empty array.
// Strings have indices as enumerable own properties console.log(Object.values("foo")); // ['f', 'o', 'o'] // Other primitives have no own properties console.log(Object.values(100)); // []
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Mar 26, 2023 by MDN contributors.
Your blueprint for a better internet.
Object.values()
The Object.values() static method returns an array of a given object’s own enumerable string-keyed property values.
Try it
Syntax
Parameters
Return value
An array containing the given object’s own enumerable string-keyed property values.
Description
Object.values() returns an array whose elements are values of enumerable string-keyed properties found directly upon object . This is the same as iterating with a for. in loop, except that a for. in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.values() is the same as that provided by a for. in loop.
If you need the property keys, use Object.keys() instead. If you need both the property keys and values, use Object.entries() instead.
Examples
Using Object.values()
const obj = foo: "bar", baz: 42 >; console.log(Object.values(obj)); // ['bar', 42] // Array-like object const arrayLikeObj1 = 0: "a", 1: "b", 2: "c" >; console.log(Object.values(arrayLikeObj1)); // ['a', 'b', 'c'] // Array-like object with random key ordering // When using numeric keys, the values are returned in the keys' numerical order const arrayLikeObj2 = 100: "a", 2: "b", 7: "c" >; console.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a'] // getFoo is a non-enumerable property const myObj = Object.create( >, getFoo: value() return this.foo; >, >, >, ); myObj.foo = "bar"; console.log(Object.values(myObj)); // ['bar']
Using Object.values() on primitives
Non-object arguments are coerced to objects. Only strings may have own enumerable properties, while all other primitives return an empty array.
// Strings have indices as enumerable own properties console.log(Object.values("foo")); // ['f', 'o', 'o'] // Other primitives have no own properties console.log(Object.values(100)); // []
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Mar 26, 2023 by MDN contributors.
Your blueprint for a better internet.
Object.entries()
The Object.entries() static method returns an array of a given object’s own enumerable string-keyed property key-value pairs.
Try it
Syntax
Parameters
Return value
An array of the given object’s own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value.
Description
Object.entries() returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon object . This is the same as iterating with a for. in loop, except that a for. in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.entries() is the same as that provided by a for. in loop.
If you only need the property keys, use Object.keys() instead. If you only need the property values, use Object.values() instead.
Examples
Using Object.entries()
const obj = foo: "bar", baz: 42 >; console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] // Array-like object const obj = 0: "a", 1: "b", 2: "c" >; console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] // Array-like object with random key ordering const anObj = 100: "a", 2: "b", 7: "c" >; console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ] // getFoo is a non-enumerable property const myObj = Object.create( >, getFoo: value() return this.foo; >, >, >, ); myObj.foo = "bar"; console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]
Using Object.entries() on primitives
Non-object arguments are coerced to objects. Only strings may have own enumerable properties, while all other primitives return an empty array.
// Strings have indices as enumerable own properties console.log(Object.entries("foo")); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] // Other primitives have no own properties console.log(Object.entries(100)); // []
Converting an Object to a Map
The Map() constructor accepts an iterable of entries . With Object.entries , you can easily convert from Object to Map :
const obj = foo: "bar", baz: 42 >; const map = new Map(Object.entries(obj)); console.log(map); // Map(2) "bar", "baz" => 42>
Iterating through an Object
Using array destructuring, you can iterate through objects easily.
// Using for. of loop const obj = a: 5, b: 7, c: 9 >; for (const [key, value] of Object.entries(obj)) console.log(`$key> $value>`); // "a 5", "b 7", "c 9" > // Using array methods Object.entries(obj).forEach(([key, value]) => console.log(`$key> $value>`); // "a 5", "b 7", "c 9" >);
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Feb 21, 2023 by MDN contributors.
Your blueprint for a better internet.