Utilize the function parameter as the key within the object being returned

I have encountered an issue with a simple block of code:

function toObj(i){
    return {
        i: i
    };
}

numObj=s=>s.map(toObj)

Whenever I provide an array of numbers to numObj, my expectation is for the key and the value to align with the argument that was input. An example of the desired result would be:

numObj([1, 2, 3, 4]) => [{1: 1}, {2: 2}, {3: 3}, {4: 4}]

However, the actual output appears as follows:

numObj([1, 2, 3, 4]) => [{i: 1}, {i: 2}, {i: 3}, {i: 4}]

I am seeking guidance on how to establish the key of the returned object to correspond with the provided argument.

Answer №1

Implementing computed property names is a great way to generate keys from values:

const createObject = value => ({ [value]: value })

const convertToObj = array => array.map(createObject)

const data = convertToObj([1, 2, 3, 4])

console.log(data)

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

Jquery display function experiencing unresponsiveness

Currently, I am trying to implement some show/hide functionality in my JavaScript file: $(document).ready(function() { $('#me').hide(); $('#send').click(function() { $('#me').show("slow"); }); }); Strange ...

Issue encountered while retrieving information from JSON structure

My data is stored in a JSON file named info.json. [ {"employee": {"name":"A", "salary": "324423"}}, {"employee": {"name":"B", "salary": "43111"}}, {"employee": {"name":"C", "salary": "43434"}}, {"employee": {"name":"D", "s ...

Attempting to develop a feature that allows users to give positive feedback, reminiscent of the popular "like" feature

Utilizing a PHP array to collect user input stored in a MySQL database, I have implemented a variable based on the num_rows function from my database. This determines the number of iterations the for loop will run through to display the values in my array. ...

Tips for identifying when v8 heap utilization in Node.js is nearing its limit

Currently, my script includes the following code: const v8 = require('v8'); let heap = v8.getHeapStatistics(); let usage = 100 / heap.heap_size_limit * heap.used_heap_size; if (usage > 90) { console.log(`V8 heap usage close to the limit ...

Saving numerical values from a document into an array

I have been working on a new algorithm that reads numbers from a file in the command prompt and stores them into an array. Here is an example of how the file looks: 12 563 898 521 Below is the code I have written for this: // INCLUDES #include <stdi ...

It is impossible to remove or trim line endings with regex in Node.JS

I'm having trouble with using process and util in a NodeJS script. Even after trimming, line breaks persist in the resulting string (as seen in the console.log() output below). I'm unsure why this is happening. var util = require("util"); proces ...

Generate 3D text with Three.js that remains stable even when zooming or panning

Current Three.js version: r79 I am looking to achieve the effect of having a 3D object (specifically a mesh created with THREE.TextGeometry) appear as if it is in a 2D space while always remaining fixed in the same position on the screen, regardless of an ...

Struggling to send a POST request to my API using AJAX and jQuery

Struggling with POST and GET requests in jQuery and javascript for my API. Managed to POST using curl request in git bash but unable to do so with JS/jQuery, also not populating on main HTML page. Below is the form code: <h2>My Lists:</h2> < ...

Constant Array Error in PHP

Hi there, I encountered an error on my hosting server while working with my PHP file. The issue seems to be related to the following line where I define a constant array: const telegram_methods=['sendMessage'=>'sendMessage','an ...

Chrome debug function named "Backbone" triggered

Backbone provides the capability to activate functions in other classes by utilizing Backbone.Events effectively. a.js MyApp.vent.on("some:trigger", function(){ // ... }); b.js function test(){ doSomething(); MyApp.vent.trigger("some:trig ...

Execute a script when a post is loaded on a WordPress page

I am looking to have my jQuery script execute every time a post page is opened or loaded. I tried using echo in the script but it did not work. Where should I place the script to ensure it runs? single.php <script src="https://ajax.googleapis.com/aja ...

The Power of AngularJS - Unlocking the Potential of Module Configuration

Exploring the concepts in this AngularJS example: angular.module('myModule', [], function($provide) { $provide.factory('serviceId', function() { var shinyNewServiceInstance; //the factory function creates shinyNewServiceInsta ...

Positioning Backgrounds with Padding in DIV Elements

I am trying to figure out how to add a check mark next to text in a button with specific styling. I have managed to get the check mark aligned properly using Background:left center, but I also want to add padding and adjust spacing. Is there a way to achie ...

Tips for transferring the id from a delete button to a delete button in a popup dialog box

In my frontend application, there is a table where each row corresponds to an item. For every row, there is a "Remove" button that triggers a warning popup upon being clicked. The intention is to pass the item's ID in this popup so that if the user co ...

The Less compiler (lessc) encounters an issue on a fresh operating system. ([TypeError: undefined is not a function])

After setting up my new development environment on Windows 10, I encountered an issue with less. Following the instructions on lesscss.org, I installed less using: npm install -g less The installation process completed without any errors. However, when ...

JavaScript - reveal/ conceal function

Just starting out with JavaScript and feeling a bit lost with this homework assignment - "I need to modify the page so that all images are hidden until the “start” button is clicked. After clicking the start button, it should change to a stop button d ...

How can default props be set for a nested object in Vue?

Here's how I've defined my props: myHouse = { kitchen:{ sink: '' } } I attempted to set the default props like this, but it didn't work as expected. props: { house: { type: Object, default: () => { ...

Refining an array data table within a nested component

Transitioning my old PHP/jquery single-page applications to VueJS/Webpack has been a journey I'm undertaking to familiarize myself with the latter technology. It involves converting a simple table that pulls data from a JSON API and incorporates filte ...

Bootstrap's pill-tab feature isn't functioning properly

Why is this tab not functioning properly? Do I need to make changes to the jQuery section? The Id and Href appear to be correct, but the tab is not working as expected. $('#v-pills-tab a').on('click', function (e) { e.pr ...

Revealing and concealing adjacent elements within a specified class

In an attempt to create a carousel that functions by hiding and showing images when the next and previous buttons are clicked, I have organized my images in a table and assigned the li elements a class of 'li'. There are four images in total, wit ...