Converting an array to an object with values in JavaScript

Can someone help me with converting an array to an object in JavaScript? I want to set each value to "true".

The initial array is:

['lastName', 'firstName', 'email']

I need it transformed to:

{lastName: true, firstName: true, email: true}

Thank you for any assistance!

Answer №1

This scenario lends itself well to utilizing the Object.fromEntries method:

const properties = ['city', 'state', 'zipCode'];
const details = Object.fromEntries(properties.map(prop => [prop, false]));

console.log(details);

Answer №2

One way to approach this task is as follows:

let items = ['category', 'quantity', 'price'];
let cart = {};
items.forEach((item) => cart[item] = true);

Answer №3

Loop through the array and set true as the value, using the elements as keys:

let newObject = {};
for (var j = 0; j < newArray.length; ++j) {
    let item = newArray[j];
    newObject[item] = true;
}
return newObject;

Answer №4

To understand how the reduce() function works, check out the documentation here. For example:

const items = ['banana', 'apple', 'orange']

const result = items.reduce((acc, curr) => ({ ...acc, [curr]: true}), {}) 

console.log(result)

Answer №5

let person = {}
let details = ['lastName', 'firstName', 'email']
    
details.forEach(function(item){
    person[item] = true
})

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

unable to access various attributes in an angular directive

I have a particular HTML setup that effectively outlines each attribute's value through a distinct "attachment" directive. These values are located in the attrs list of said directive, which is within a modal file upload form. <p>For Testing Pu ...

The main React component fails to fully load the index.html file

I am a beginner in the world of reactjs and I have encountered a problem with loading CSS in the head and JS libraries and plugins at the end of the body in my template. Here is how my index.html looks: <!DOCTYPE html> <html lang="en"> <hea ...

JS client-side form validation involves communicating with the server to verify user input

I currently have an HTML form that is being validated on the client side. Below is a snippet of the code: <form id='myForm' onsubmit='return myFormValidation()'> ... </form> Now, I want to incorporate server-side valida ...

JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles. The function randomly selects a border color for each circle, and this feature is functioning correctly. To enhance the appearance, I decided to add a box shadow to the circl ...

What methods can I employ to utilize PHP or JS/HTML for posting to two separate URLs simultaneously?

Is it possible to submit a form from one button to two different locations? I am looking for a solution to achieve this. After clicking the submit button on a form, the form tag looks like this: <FORM ACTION="http:site.com/servlets/RequestServlet" met ...

Instructions for filtering content by manually entering numbers and utilizing Angular 2

Having trouble filtering table contents with multiple fields? Let's take a look at the code: https://i.sstatic.net/jfLbz.png HTML: Here is the code snippet for filtering data: <ng-select [options]="name" [(ngModel)]="filter.name"></ng-selec ...

Python does not return the AJAX request back to JavaScript unless JQuery is not utilized

I have set up an XMLHTTPrequest in my javascript code to communicate with a flask location. Here's how I am doing it: var ourRequest = new XMLHttpRequest(); ourRequest.open("GET", "makeDiff") diff = ourRequest.send(); console.log(diff); Once the req ...

Tips for utilizing JavaScript to engage with a Cisco call manager

Our team is currently working on an IVR web application built with node js. I am wondering if it is feasible to integrate with the cisco unified call manager directly through node js in our web application? ...

Having trouble with adding an event listener on scroll in React JS. Need assistance in resolving this issue

I'm having trouble adding an event listener for when a user scrolls in my web app. componentDidMount = () => { let scrollPosition = window.scrollY; let header = document.getElementById("topBar"); window.addEventListener(&ap ...

Retrieving the value of a radio button using JavaScript

I am working with dynamically generated radio buttons that have been given ids. However, when I attempt to retrieve the value, I encounter an issue. function updateAO(id2) { var status = $('input[name=id2]:checked').val(); alert(status); ...

Unexpected behavior: Axios post still enters catch block despite successful completion of Rest API call

Having an issue with my axios post request not returning the value from the API in a non-success scenario (401 error). It works fine for successful scenarios. When using Postman to test the output of my reset password API by providing an incorrect current ...

Missing Values in jQuery Variable

I'm having trouble with adding a link after a block of text. Although the links render fine, the href tag seems to disappear. var eventstuff = data.text; var eventElement = $("<div class='well well-sm eventsWells'>"); var deleteButton ...

detect and handle errors when deploying the Node.js function

I'm currently attempting to use code I found on Github to insert data into a Firestore database, but unfortunately, I keep encountering an error. Here's the specific error message: 21:1 error Expected catch() or return promise/catch-or-re ...

Combining multiple layers of PHP arrays within

In contrast to other posts, my query has a unique twist as I do not possess another array to combine. Instead, I aim to merge arrays within a multi-dimensional array to transform it into a single-dimensional structure. Presented below is the existing arra ...

To implement the replacement of text with a selected item in AngularJS, simply

I have a dropdown in my HTML: <div class="dropdown"> <button class="dropdown-toggle" type="button" data-toggle="dropdown" ng-model="yearName">Filter by year <span class="caret"></span></button> < ...

Extracting data on an AngularJS platform by using web scraping techniques

I have been working on an AngularJS application that currently retrieves JSON data from an API using http.get, and it's been working really well. Recently, I've been exploring the idea of passing a URL to a static webpage and scraping the result ...

Guide on utilizing vue-router and router-link for managing links that are dynamically generated within jquery modules like datatables

I spent some time trying to "integrate" datatables.net (https://datatables.net/) into a Vue app. After some trial and error, I came across advice suggesting not a direct integration approach, but rather utilizing jquery modules as they are and "hooking" t ...

Is it possible to combine the use of 'res.sendFile' and 'res.json' in the same code?

At the moment, my Express app utilizes a controller to manage routing. When a specific route is accessed, I trigger pagesController.showPlayer which sends back my index.html. This is what the controller looks like: 'use strict'; var path = requ ...

Firestore/Javascript error: FirebaseError - The data provided is invalid for the DocumentReference.set() function. An unsupported field value of 'undefined'

I keep encountering this error Error creating user: FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field diabetesComplication) After some investigation, I realized that the iss ...

Create a compile-time array that is the result of adding two other compile-time arrays together

Imagine having two constexpr arrays (type[N] or std::array<type, N>) constexpr int X[5] { 9, 8, 7, 6, 5 }; constexpr int Y[5] { 1, 2, 3, 4, 5 }; Would you be able to create a new constexpr array by applying an element-wise operation (or constexpr f ...