Transforming a JavaScript map into an array of objects

Given a map of key value pairs that I cannot control, I am tasked with converting them into an array of objects in a specific format.


    let paramArray1 = [];
    let paramArray2 = [];

    paramArray1.push({username:"test"})
    paramArray1.push({password:"test"})
    paramArray1.push({contentType:"application/json"})



    let map = new Map();
    map.set("username","test");
    map.set("password","test");
    map.set("contentType","application/json");



    for (const [key,value] of map.entries()){
      paramArray2.push({key,value})
    }



    console.log(paramArray1);
    console.log(paramArray2);

Upon running the provided code, you will observe two outputs. While both arrays contain the same elements, the second array needs to match the format of the first one.

Is there a way to convert a map of key-value pairs into an array without separating them into key: [key], value: [value], and instead maintain the {key:value} format seen in the first array?

If you execute the code, you will encounter the issue. Thank you for your help!

I attempted to change the comma to a colon, but this resulted in using the word "key" instead of the actual key. The output for the modified code was: [{key:test, key:test, key:application/json}]


    for (const [key,value] of map.entries()){
      paramArray2.push({key:value})
    }

Answer №1

To achieve this, you should use the syntax paramArray2.push({[key]: value})

let arrayOne = [];
let arrayTwo = [];

arrayOne.push({
  name: "example"
})
arrayOne.push({
  email: "example@example.com"
})
arrayOne.push({
  role: "admin"
})

let map = new Map();
map.set("name", "example");
map.set("email", "example@example.com");
map.set("role", "admin");

for (const [key, value] of map.entries()) {
  arrayTwo.push({[key]: value})
}

console.log(arrayOne);
console.log(arrayTwo);

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

The required element was not discovered

Whenever I attempt to execute npm run serve, it reaches 98% completion and then halts, displaying the following error message: An issue occurred while compiling with a total of 1 error: ...

The useRouter() function doesn't seem to be successfully navigating to the main landing page

"use client" import { useState } from 'react'; import {auth} from '../../firebase-config' import {createUserWithEmailAndPassword} from 'firebase/auth' import { useRouter } from 'next/router'; const SignUp = ...

Unable to reference the namespace 'ThemeDefinition' as a valid type within Vuetify

Looking to develop a unique theme for Vuetify v3.0.0-alpha.10 and I'm working with my vuetify.ts plugin file. import "@mdi/font/css/materialdesignicons.css"; import "vuetify/lib/styles/main.sass"; import { createVuetify, ThemeDefinition } from "v ...

A web application using JavaScript and Node.js with a focus on creating a REST

After extensive research, I am eager to develop a web application using JavaScript and Node.js with an SQL back-end. However, the abundance of frameworks and tools available has left me feeling overwhelmed. While I have identified some that I would like to ...

Switching the keyboard language on the client side of programming languages

I'm interested in altering the keyboard language when an input element changes. Is it possible to modify the keyboard language using client-side programming languages? And specifically, can JavaScript be used to change the keyboard language? ...

Entry module could not be located due to an unresolved 'babel-loader' error

As a newbie to the world of React, I found myself facing an issue while setting up the installation and loading all the necessary dependencies. Upon running the npm start command, I encountered the following error message: ERROR in Entry module not found: ...

Transform an array through reference manipulation

From my MySQL database, I am fetching a nested array structure Array ( [0] => Array ( [page] => categorypropose [value] => baby-sitters [id] => 357960 ) [1] => Array ( [page] => categorysea ...

Are `<text>` nodes unable to utilize ligature fonts in CSS/SVG?

Check out this JsFiddle demo: http://jsfiddle.net/d0t3yggb/ <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <div class="material-icons">add add add add</div> <svg width="100%" height="100% ...

Position does not exist

I'm currently working on developing an application form that can be submitted by applicants based on the position they are interested in. However, I am facing an issue when trying to click submit on the application form, resulting in the error display ...

Utilize a for loop in Vue.js to save a fresh array of objects in a structured format

Trying to achieve the following using Vue: I have two JSON objects that provide information on languages and the number of inputs per language. Using nested loops, I display all the inputs. My goal is to create an object for each input with additional det ...

What can be used instead of makeStyles in Material UI version 5?

My journey with Material UI version 5 has just begun. In the past, I would utilize makestyles to incorporate my custom theme's styles; however, it appears that this method no longer works in v.5. Instead of relying on {createMuiTheme}, I have shifted ...

What is the process of displaying JSON headers using JavaScript?

Although it may seem like a simple question, I am new to JSON. Can someone explain how to display a heading in the console? This is the code I have: var jsonstr = '{"profile":{"name" : "raj","age":"35&qu ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

unable to utilize references in React

import React, { Component } from "react"; class Learning extends Component { firstName = React.createRef(); handleSubmit = event => { event.preventDefault(); console.log(this.firstName.current.value); } ...

Extract the innerHTML input value of each row in an HTML table

I've encountered an issue with my HTML table that contains static values, except for one cell which has an input field. When I try to convert the row data into JSON, the single input field is causing complications. Without the input field, I can suc ...

Tips on resolving JavaScript's failure to adjust to the latest HTML inputs

I'm working on a homepage where users can choose their preferred search engine. The issue I'm facing is that even if they switch between search engines, the result remains the same. I've experimented with if-then statements, but the selecti ...

Develop a GWT overlay specifically designed for a deeply nested JSON data structure

Recently stumbling upon this amazing site, I find myself compelled to seek your assistance with a particular issue: How do you go about accessing the fields within the nested JSON object labeled "flightLegs" from the main JSON object "flights"? When it c ...

Delivering create-react-app's build files through an express server

I am trying to serve the build files of my React app on another Express application. I have copied all the static files from the build folder to the public folder inside my Express application and have set up the following code: app.use(express.static(pat ...

Consider yourself a module for npm, just like a node

I'm currently working on a Javascript project that has been released as a node module. In some parts of the source code, I have used relative paths to import other files within the project: // <this_module_path>/action/foo.js import execution f ...

The sequence of text is not appearing correctly

I'm attempting to populate a paragraph with JSON data, while inserting a divider between data gathered on different dates. function fetchAllLogs(employeeId) { $.getJSON('datafile.json', function(data) { $("#" + employeeId).html( ...