Rewriting JavaScript: Converting an Array of Objects to an Object.
In my adventures to better understand Javascript I have come across many amazing (functional) solutions to everyday problems. But one has always stumped me to no end, well, until just recently that is. Converting an Array of Objects to an Object (in a good functional way!).
The Problem
First lets give a small snippet of code…
The snippet is quite simple, an array of people objects where each object contains id, name, and age.
For this problem lets assume you have been given the peopleArray and an id of the user and need to select them from the peopleArray.
Below is a snippet of how you would normally select the user:
This is fairly simple and will traverse the array and assign the correct person to selectedPerson. This presents many problems though, mainly it introduces mutation into your code. Scary!
The Solution
For me the ideal solution would be to convert the array into an object that looks like the following:
If our data is organized in this format you can simply select a person based on their id. Preventing the need to traverse an array!!
This is much cleaner, and removes mutation and complexity from our code base. But in many cases you may not be able to control the format that the data is presented to you. So it may be best to convert that data on the fly. Luckily ES6 provides us a way to make this conversion.
Note: If you have not learned about Array.reduce() now is the time to do so. One of my past articles has links to resources about using Array.reduce() as well as an example and simple explanation.
What we do in the snippet above is use reduce, which returns accumulator (obj), to which we append each item in the array using that items id. This will convert our array of objects into an object of objects. YAY! (If reduce is confusing you please please please go check them out here! They are freakin amazing!)
The problem is that this snippet is limited to objects where the new object key is going to be id. Lets abstract this so the function is re-useable in all situations!
The above code now accepts a keyField which allows us to use this function to convert any array of objects. Not just those who have an the field id. This is important for reusability of our code.
Conclusion
By converting our array of objects to an object of objects, in a functional way of course, we have limited the need for mutation in our codebase! If you want a bit more information on why it may be better to store your data in objects instead of arrays check out this article by Firebase.
Thanks!
Thanks for reading! I’ll be covering more topics in the near future about rewriting basic Javascript concepts using the new standards.
Useful Reading
-
— covers ES6 topics by the guys who implemented it in Firefox! — with a simple example I wrote and links to reading by people smarter than I.
Additions/Edits
As pointed out by @joaoeffting (thanks for pointing it out!) to perform the same operation on the original array in one line to find the selected user is super simple:
This is a fantastic solution when you need to access the data in one off situations, or if you just prefer your data to stay in the array format.
Additionally Taq Karim pointed out a killer single line solution that eliminates the return statement and makes fantastic use of the spread operator. Absolutely great solution thats super exciting and really shows off Javascripts power and syntax! Thanks again Taq Karim!
Please leave a comment below with questions, concerns, or cake (bring cake if you're going to roast me)!
Преобразование массива в объект в JavaScript
Массивы и объекты считаются очень важными в JavaScript. Оба являются изменяемыми и могут хранить некоторые значения в JavaScript.
Мы используем массивы, когда храним несколько значений в одной переменной, в то время как объект может содержать несколько переменных с их значениями.
Как правило, при больших объемах данных использовать объекты быстрее.
В этом руководстве мы узнаем, как преобразовать массив в объект в JavaScript.
Используйте метод object.assign() для преобразования массива в объект в JavaScript
Метод assign() может итеративно считывать свойства одного или нескольких объектов в целевой объект. Возвращает целевой объект.
Проверьте код ниже.
Используйте метод array.reduce() для преобразования массива в объект в JavaScript
Метод reduce() может применять функцию (которую вы предоставляете) к каждому элементу массива. Он возвращает одно выходное значение.
Мы можем использовать его для необходимого преобразования.
Использование оператора Spread для преобразования массива в объект в JavaScript
В JavaScript оператор распространения ( . ) может распаковывать все элементы массива. Мы можем использовать его для преобразования массива в объект.
Object.fromEntries()
The Object.fromEntries() static method transforms a list of key-value pairs into an object.
Try it
Syntax
Parameters
An iterable, such as an Array or Map , containing a list of objects. Each object should have two properties:
A string or symbol representing the property key.
The property value.
Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value.
How to Convert an Array Into an Object Using JavaScript
![]()
How do you convert an array into a new object using Javascript?
You can convert an array into an object using one of these three methods:
- The Object.assign() function
- Loop over the array and construct a new object
- The reduce() function
We’ll go over each of those methods in this article and provide some code examples for you to use on your website or application.
Let’s get started!
Table of Contents
1. Object.assign()
Object.assign() is the first method we’ll cover for converting an array to an object. This method is used to copy values from one or more source objects to a new object.
The function takes two parameters:
- The target object you wish to modify (this will be returned by the function)
- The source object of where to extract the properties from
If you give the function an array as the source data, it will loop over each item in the array and create a new object where the key is the array index of the value.
Here’s what it looks like in practice:
Notice how each item in the new object uses the array index of the value as the key (i.e. «0» , «1» , etc.).
And you can now access each item in the new object using the conventional dot notation method ( foo.bar ).
In the next section, we’ll show you how to manually loop over an array to construct a new object.
2. Loop Over Array & Construct a New Object
For the second method, we’re going to loop over each item in an array and add each of its values as a new property in a new object. To match the object returned in the last section, the key value will be the array index for each item.
In the code example, we’ll be using a for loop to enumerate over each item in the array. But, you can use any other method of looping over an array that you wish ( while , while/do , etc).
Here’s the full code example:
First, we declare an empty object called newObject that will serve as the new object that’ll hold our array items.
Then, we use a for loop to iterate over each item in the array. If the value doesn’t have an undefined value, we add the item as a new property to the newObject using the array index as its key value.
If you console.log() the new object, you’ll see that the same object as the first method is returned.
3. Reduce()
The last example we’ll show you is the reduce() method. The reduce() method executes a given function for each item of the array and stores the values in an accumulator entity, which will be an object in the case we’re using it for.
We’ll call the reduce() function directly on the array and give it a parameter function that constructs a new object using each item in the array. The array index value will be used as the object key.