Obtain the value from a JavaScript array and use it as the key

Below is an array containing objects:

objectArray = [{name: “E-mail”, data_type: “text”}, {name: “Number”, data_type: “text”}, {name: “Person”, data_type: “text”}]

The goal is to extract only the name property from each object and use it as a key in a new object as shown below:

counterObject = {E-mail: 0, Number: 0, Person: 0}

An attempt was made to achieve this using the map method like so:

objectArray.map((elem) => {
                return {[elem.name]:0};
            })

However, the result obtained was:

[{Text: 0}, {Number: 0}, {E-mail: 0}, {Person: 0}, {Upload: 0}, {Date: 0}, {Link: 0}] 

Answer №1

const data = [{ key: "E-mail" }, { key: "Number" }, { key: "Person" }];

const output = {};
data.forEach(item => output[item.key] = 0);

console.log(output);

Using the reduce method can be an alternative, however, I find it to be less understandable and has the downside of repeatedly creating/shallow-copying the accumulator.

Answer №2

If you want to achieve this, you can utilize the reduce method like so:

const dataArr = [{name: "E-mail", data_type: "text"}, {name: "Number", data_type: "text"}, {name: "Person", data_type: "text"}];

const output = dataArr.reduce((res, obj) => ({ ...res, [obj.name]: 0 }), {});

console.log(output);

Answer №3

give this a shot

const extractedKeys = {};

objectArray.forEach(obj => {

     extractedKeys[obj['name']] = 0;
});

console.log(extractedKeys);

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

Developing an array-based multiple choice quiz

Being a complete novice, I am currently immersed in designing a multiple-choice quiz using arrays. The questions all follow a similar template: "Which word in the following has a similar meaning to '_________'." To implement this, I have created ...

Ways to refresh the main frame

Here is an example of parent code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Parent</title> </head> <body> <iframe src="https://dl.dropboxusercontent.com/u/4017788/Labs/child.html" width ...

Retrieving information from a URL stored in a JSON document

Trying to access data from a JSON file whose URL is nested in another JSON file can be quite complex. Let me simplify what I'm looking for: I want to retrieve all the contributors and the last hundred commits of a specific repository on GitHub. To a ...

Discover the pixel width of a Bootstrap grid row or container using JavaScript

How can I calculate the width of a Bootstrap grid row or container in pixels using JavaScript? I am working with Aurelia for my JavaScript project, but I'm open to solutions in standard JS (no jQuery, please). Looking at the Bootstrap documentation, ...

Showing a div with a smooth fade-in effect while switching its display property to inline using jQuery

Currently, I am working on a project that involves implementing a "side pop up". To ensure it doesn't flicker like it does with jQuery's "hide()" method, I want to start by setting the display property to none using CSS. My main question is: - Ho ...

What is the process for sending a JSON response and then redirecting to an HTML page after a successful event in Node.js using Express?

Trying to send a JSON response and redirect the page simultaneously in Express.js. Need help figuring out how to achieve this. Is it possible to redirect in Express.js while sending a JSON response to the client? The goal is to use this JSON data to render ...

Using orchestrate.js for local passport.js authentication

I need assistance finding a tutorial or resources for setting up local passport.js authentication with Orchestrate as the user storage. Most of the resources I have come across are based on MongoDB, but our project requires us to use Orchestrate. Any advic ...

Challenges with UV wrapping in THREE.js ShaderMaterial when using SphereBufferGeometry

Currently, I am attempting to envelop a SphereBufferGeometry with a ShaderMaterial that incorporates noise to mimic the surface of Jupiter. However, the wrapping on the sphere geometry is turning out peculiarly. Instead of wrapping around the 'planet& ...

Unable to retrieve information from v-for as it returns null data

Currently facing an issue with retrieving data from the database using Axios in Vue.js. I am able to see the data in my database through Vue.js developer tools like this: https://i.stack.imgur.com/n7BRO.png However, when attempting to loop through the dat ...

Transform Array into an unordered list with list items

Currently, I am dealing with a file that contains strings of file paths in the following format: ./CatDV/S1/SFX/steam/6004_90_04 LargeHeadlightSm.wav ./CatDV/S1/SFX/steam/AirHissPressureRe HIT032001.wav ./CatDV/S1/SFX/steam/Impact_Metal_Bullet_Hit(1).wav ...

The system seems to be having trouble locating the password property, as it is returning a value of

I'm currently working on a database project using MongoDB and Node.js. I'm trying to update a specific field, but unfortunately I keep getting an error. The model I am working with is called "ListaSalas": router.post('/updatesala', fun ...

Retrieving projectname values with specific name from a table

Currently, I am in the process of developing a website for myself and my friends to collaborate on projects together, similar to Google documents. One challenge I am facing is retrieving project names from a MySQL table. This is what I have attempted so f ...

What would be the best way to set up .replace(/./g, '_') to exclude spaces from being replaced?

After completing my first jQuery project, a simple hangman game featuring one-word book titles in the word bank, I am eager to enhance it to accommodate multi-word book titles. However, I am unable to find the necessary information to modify my code. Curr ...

"The combination of Node.js, Express, and Angular is causing a continuous loop in the controller when a route is

Currently, I am utilizing node js alongside Express. Angular js files are being loaded through index.html. The code for app.js is as follows: app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); ...

What is the best way to apply toggle function to reveal hidden elements?

Imagine you have an HTML page with a button on it. When the button is clicked, a toggle appears containing another button: (Code inside the toggle) <button id="new">New</button> You try to remove this button using jQuery: $('#new' ...

What could be causing the issue with the $http.delete method in AngularJS?

When trying to use $http.delete with Django, I encountered an HTTP 403 error. Here is my JS file: var myApp = angular.module('myApp',['ui.bootstrap']); myApp.run(function($http) { $http.defaults.headers.post['X-CSR ...

What is the process for importing module functions in Svelte when utilizing npm?

I'm having trouble understanding how to properly use imports in Svelte with npm. I have a Svelte component that I can't seem to get working. Uncommenting "//import { Configuration, OpenAIApi } from "openai";" leads to the error message: [!] (plug ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

Use ajax.net 6 core to upload a file to the wwwroot directory

Hi there! I'm trying to figure out how to upload a file to wwwroot/upload_files using ajax and .net. I have the backend setup and the file gets uploaded to the location successfully. However, I'm having trouble making it work with ajax, or maybe ...

What is the solution for untangling this complicated Javascript variable referencing issue?

Currently facing an issue that needs to be addressed: app.controller 'MainCtrl', ($scope, TestData) -> $scope.name = 'World' TestData.get(0).then (data)-> $scope.elem = data TestData.get(1).then (data)-> $scope ...