Using array object in javascript

What is an Array of Objects in JavaScript?

some more fun with Objects

An array in javascript is the collection of multiple types of data at a single place in order, and an array of objects in javascript is a collection of homogenous data, that stores a sequence of numbered objects at a single place.

Above, there is an array of objects myArr and we are accessing an object from the array by using array index myArr[1] , also printing the value on the console. As result, we are printing an object from an array of objects. This prints all the key-value pairs present at that particular index.

Syntax

Creating an Array of Objects

To create an array of objects in javascript, we have to declare an empty array first and then initialize it with the objects separated by a comma.

Читайте также:  Instance factory method in java

Above, we declared an array of objects where each array is separated by a comma and has three properties in each.

Array Properties

There are three types of properties in array Object: 1. Constructor — The constructor properties return a function that creates the Array prototype. This return function is a native code that is provided by the javascript engine.

Above, we have an array of objects myArr and we are printing its constructor properties on the console. As result, we print the function Array() < [native code] >on the console.

Here, we get the native code as a reference which is a predefined function inside the javascript engine responsible for creating the Array prototype.

2. Length — It returns the length of elements in an array i.e. the number of objects present in the array.

Above, we use the length properties on the myArr array of objects and also print it on the console. As result, we print 2 on the console.

3. Prototype — Array Prototype property helps to add new methods into the Array, for example- adding all values into an array. It also helps to add properties to the Array Object.

Above, we are adding a user-defined method into the Array Object. To do that, we accessed the Array prototype property using dot notation and added the user-defined function add into Array Object like this Array.prototype.add . Then, assigned an anonymous function to add , which is the definition of add method.

In the add method definition, we declare a result variable to store the array value count. Here, we are using the this keyword to reference the array on which the add method will get called and looping over the array. In each iteration, we are accessing the individual array values and adding them to the result variable, when all values inside the array get added to the result variable, we returned the final result .

Array Methods

Array methods are predefined methods into the Array Object prototype property. To use the array methods we call it on an array using object dot notation, using bracket notation will cause an error.

These are some frequently used array methods:

Array.push()

The push method helps to add a new value at the end of an array. To use it, we have to call the push method on an array by passing the value we want to add as a parameter. We can pass a single value as a parameter or multiple values separated by a comma.

Above, calling push method upon myArr array by passing a value 4 as a parameter also printing myArr on the console. As result, value 4 gets added at the end of myArr array, and [1,2,3,4] get printed on the console. The time complexity of the push method is O(1) and space complexity is O(N), where N is the length of the input.

Array.pop()

Array pop method helps to remove the last value from an array, it gives the removed value in return. To use it, we have to call pop() method on an array, which doesn’t take any parameter.

Above, we have myArr array on which we are calling pop method. As result, the last value of the array myArr gets removed. Time complexity of the push method is O(1) and space complexity is O(1).

Array.shift()

Array shift method helps to remove the first value from an array, and in return, it gives the removed value. To use shift method, we have to call it on an array, and it doesn’t take any parameter.

Above, we have myArr array on which we are calling shift method. As result, the first value of the array myArr gets removed. Time complexity of push method is O(n) and space complexity is O(1).

Array.unshift()

Unshift method unshift to add a value at the beginning of an array. To use it, we have to call it on an array by passing the value we want to add as a parameter. We can pass a single value as a parameter or multiple values separated by a comma.

Above, calling unshift method on myArr array by passing a value 4 as a parameter. As result, value 4 gets added at the beginning of myArr array. Time complexity of push method is O(n) and space complexity is O(N), where N is the length of the input.

Array.slice()

Array slice method helps to copy an array without affecting the original array. To use it, we have called it on an array by passing the first and last index of the subarray we want to copy, but the value of the last index will not be included in the copied subarray. Leaving parameters blank will result in slice method default behavior, which will copy the whole array from index [0] to [n].

Above, we have myArr array on which we are calling slice method by passing first index 1 and last 3 as parameters. As result, we copy the subarray from index [1] to [3] which is [2,3]. Time complexity of slice method is O(n) and space complexity is O(N), where N is the length of the input. Time complexity of push method is O(n logn) and space complexity is O(N), where N is the length of the input.

Looping through an Array of Objects

We can loop through an array of objects using the for loop but available array methods make it much easier. So, we are going to use the map method to loop through an array of objects.

Above, we loop over an array of objects myArr using map method, in each iteration again looping over the individual objects and printing the properties key-value pair on the console. As result, we printed all the array object’s properties on the console.

Conclusion:

  • Array of objects in javascript is just an array having object data as its value.
  • Array methods are predefined methods that help to perform various operations on an array.
  • To make an array of objects in javascript, we have to declare an array and then add the object’s data as its value.

Источник

JavaScript Array of Objects Tutorial – How to Create, Update, and Loop Through Objects Using JS Array Methods

Ondrej Polesny

Ondrej Polesny

JavaScript Array of Objects Tutorial – How to Create, Update, and Loop Through Objects Using JS Array Methods

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:

categories

Considering each category list item looks like this in HTML:

code

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:

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

beginning

To add an object at the first position, use Array.unshift .

Add a new object at the end — Array.push

ending

To add an object at the last position, use Array.push .

Add a new object in the middle — Array.splice

middle

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 .

cars-colorred

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 .

cars-colorred2

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.

cars-sizes

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.

cars-sort

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?

sort

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 🙂

Источник

Оцените статью