Converting a JavaScript map into an array with ES6: A step-by-step guide

I am in need of a solution to convert a JavaScript map into an array with a specific format:

[
  {
    name: "21 years old",
    totalUsers: 2,
  },
  ...
]

For example, if I have the following map:

const ages = {
  "21": 2,
  "18": 10,
}

The function called "parseAges" should return:

[
  {
    name: "21 years old",
    totalUsers: 2,
  },
  {
    name: "18 years old",
    totalUsers: 10,
  },
]

This is how I am currently accomplishing this using for...of in ES2017:

const ages = {
  "21": 2,
  "18": 10,
}

function parseAges() {
  const agesArr = [];

  for (const [key, value] of Object.entries(ages)) {
    agesArr.push({
      name: `${key} years old`,
      totalUsers: value
    })
  }

  return agesArr;
}

console.log(parseAges());

Is there a way to achieve the same result without using for...of, in ES6?

Answer №1

My approach to this problem involves using for...of in ES2017:

for/of is a feature introduced in ES6 (ES2015).

Is there a way to achieve the same result without using for...of in ES6?

There hasn't been any specific syntax introduced in ES6, aside from for/of, that would simplify this task compared to using older or newer syntax.

Object.entries provides an alternative approach in ES2017 (ES2017):

const list = Object.entries(ages).map(([age, users]) => ({
  name: `${age} years old`,
  totalUsers: users,
}));

Object.keys is another alternative in ES5/ES2009:

const list = Object.keys(ages).map((age) => ({
  name: `${age} years old`,
  totalUsers: ages[age],
}));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Breaking down the initial state within a redux reducer

Can you explain the distinction between returning state in the default case of a Redux reducer using return state and return { ...state } ? ...

Swapping values between HTML tables and arrays with the power of JavaScript

I have a unique table structure that I need help with: https://i.sstatic.net/fr7oJ.png My current table has 2 rows and multiple columns, but I want to change it to have 2 columns and multiple rows like this: https://i.sstatic.net/uhkp9.png To create th ...

Adding to the beginning of a list in JQuery mobile

Having trouble figuring out how to prepend my list in jQuery mobile while keeping the divider on top of the most recent item added. I attempted to prepend the newly added item, but it ended up shifting the divider to the bottom instead. function loadScan ...

The this.setState method does not seem to be properly updating the nested array within the user object. However, when checking the same logic using console.log, the object

When the user selects multiple meals, they are stored in an array of objects inside the user object. Upon clicking submit, the code utilizes setState to update the user's meals as follows: submitAllMeals(arrayOfMeals) { this.setState({ u ...

What is the best method to update numerous low-resolution image sources with higher resolution images once they have finished loading?

I'm currently developing a website that implements a strategy of loading low-resolution images first, and then swapping them for high-resolution versions once they are fully loaded. By doing this, we aim to speed up the initial loading time by display ...

Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. De ...

Troubleshooting Django Python: Why can't I retrieve a JS object sent via AJAX in my Python QueryDict?

As I work on my Django project, I've set up a system for data exchange between the server and client using javascript and python with AJAX. To make things easier, I created a config object in JS to store important parameters that both the server and J ...

Encountering a timeout error while using selenium-webdriver and phantomJS

Currently, I am developing my automated test scripts using a combination of selenium-webdriver, phantomJS, and mocha. The script I am working on is written in JavaScript. One requirement is to wait until a specific element becomes completely visible befo ...

Refresh collection of texts

I am attempting to update an item within a subarray of a document. The type of the subarray is an array of strings: Dictionary.findOne({ name: req.query.name }, function(err1, data){ if(err1){ logger.error(err1); res.send({ ...

"Strategically placing elements on an HTML grid

My current project involves creating a grid layout in HTML using CSS. The goal is to use this layout for various elements such as images, text, and links. What I envision is a visually appealing grid where each object fits together seamlessly with no gaps ...

How can you sustain a backend connection using NodeJS as users navigate through different pages?

Currently, I am establishing connections through thrift (node-thrift) with a backend server for api calls. The communication is bidirectional (push/pull) to NodeJS. As users navigate various URLs and Node serves jade templates and javascript files using C ...

Tips for updating a value in a React TextField using handleChange function

After clicking a button, I need to dynamically set a value in this textfield: <TextField fullWidth inputProps={{ maxLength: 75 }} key="nomeSocial" id="outlined-basic" label="Nome Social" name="nomeSocial&qu ...

When a value is deleted from an input in jQuery, all other changes become void

I am experiencing an issue with Javascript where even after deleting or changing the value of a field, jQuery effects still persist. Is there a way to reset all changes made when the input value is deleted? For example, you can visit , type 6 in and then ...

Is it beneficial to vary the time between function calls when utilizing setInterval in JavaScript?

My website is displaying two words one letter at a time, with a 0.1s delay between letters and a 3s pause after each full word. I attempted using setTimeout, but it's not functioning as expected. What could be the issue in my code? var app = angular. ...

Efficiently uploading multiple files using AJAX in conjunction with Codeigniter

Greetings! I'm attempting to utilize ajax and codeigniter to upload multiple images. As a beginner in ajax and jquery, I would greatly appreciate any assistance in identifying where I might be going wrong or missing something. Below is my controller ...

Tips for Organizing an Array: Grouping Categories and Products

I have a single array and I am looking to separate categories from the products listed within it. const product = [{ id: 1, name: 'Cloth', cat: ['fashion', 'man', 'women'] }, { id: 2, name: &apos ...

Ensuring the validity of float and non-empty values in JavaScript

Embarking on the journey of web development, I'm delving into basic applications. My current project involves creating a straightforward webpage to add two numbers and implementing preliminary validations - ensuring that the input fields are not left ...

Styling with CSS: Using a Base64 Encoded Image in the Background URL

Can a Base64 encoded image be loaded as a background image URL without exposing the actual encoded string in the page source? For example, if a Node API is used to GET request at "/image", it returns the serialized Base64 data. res.json("da ...

JavaScript Dynamic Array for Generating GoogleChart JSON Data

I am attempting to create a line chart using Google Charts ( ), but I am struggling with formatting the array for the chart. The required array format is as follows : var data = google.visualization.arrayToDataTable([ ['Year', 'Sales&ap ...

Leveraging the power of async to streamline the serialization of operations with numerous layers of callbacks in Node

I'm relatively new to working with node.js and I'm encountering difficulties in understanding callback functions. The issue arises when I need to execute a series of complex operations that involve a lot of code divided into modules with numerous ...