Use the spread operator to assign a value to the keyname

Would it be possible to dynamically assign key names to the spread operator?

For instance, consider the following:

'first, second, third'.split(',');
// Array(3) : [ 'first', 'second', 'third' ]

I would like to create an object like this

{ 'first': 'first', 'second': 'second', 'third': 'third' }

Currently, when attempting this, I receive:

{ ...'first, second, third'.split(',') };
// { 1: 'first', 2: 'second', 3: 'third' }

Is there a way to dynamically set this or must it be manually done through iteration?

I have managed to merge two answers together and use the following solution:

const toObject = str => Object.assign(...str.split(/\s*,\s*/).map(key => ({ [key]: key })));

Answer №1

An efficient way to convert a list of key/value pairs into an object is by using the spread operator and Object.assign:

const keyValuePairs = 'apple, banana, cherry'.split(',').map(pair => ({[pair]: pair}));
const object = Object.assign({}, ...keyValuePairs);

Answer №2

Jonas' idea is quite innovative. I appreciate it. Here is another approach:

function convertToObject(inputString) {
  const parts = inputString.split(/\s*,\s*/);
  return parts.reduce((object, part) => {
    object[part] = part;
    return object;
  }, {});
}

console.log(convertToObject('alpha, beta, gamma'));

It's worth noting that I have utilized split(/\s*,\s*/) instead of split(',') to remove any spaces between elements.

If you prefer a condensed version, you can achieve it with the following one-liner:

const convertToObject = inputString =>
  inputString.split(/\s*,\s*/).reduce((o, p) => (o[p] = p, o), {});

console.log(convertToObject('alpha, beta, gamma'));

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

What is the best way to use element.appendChild to generate a link?

I am currently utilizing the following snippet of Javascript to extract information from the current webpage using a browser extension. I have only included a portion of the code that is relevant, as the full script is quite lengthy. The code works perfect ...

Transfer the AWS configuration settings to the imported module

Currently, I am attempting to perform unit testing on a JS AWS Lambda by running it locally. To simulate the Lambda environment, I am taking on the same role that the Lambda would have with AWS.config.credentials and then executing the Lambda function that ...

Tips for preventing a React component from re-fetching data when navigating back using the browser button

In my React app using Next.js and the Next Link for routing, I have two pages set up: /product-list?year=2020 and /product-list/details?year=2020&month=4 Within the pages/product-list.js file, I am utilizing React router to grab the query parameter ye ...

Disabling tooltip functionality on an element

Trying to figure out how to remove a tooltip from an element once the text is no longer truncated. The challenge lies in not being able to access the event of the tooltip itself. The tooltip is added by setting an attribute on truncation, but simply removi ...

The functionality of Bootstrap toggle ceases to operate properly following an AJAX content update

I am currently using AJAX load to fetch some content on my webpage. I am working with Bootstrap 3 and Bootstrap toggle. When the content is loaded, the Bootstrap 3 content functions properly (the panel-primary panel is clearly visible). However, the Bootst ...

Top method for utilizing render props in React

Currently, I am employing render model props. However, I have a hunch that there might be an alternative method to achieve the same outcome. Is anyone familiar with another approach? {variable === "nameComponen" && <component/>} {variable === "name ...

Fetching server-side JavaScript source from a relative path within an ASP file

My setup involves a local IIS server pointing to a virtual workspace at c:\projects Within my c:\projects directory, I have the following folder structure: Game src asp test.asp jquery jquery.min.js The test ...

Ways to create a minimatch glob that selects every js file except those within a specific folder

I am currently facing a situation where I require a single glob pattern, utilizing minimatch, to match all JavaScript files except those in a specific directory. Unfortunately, the tool I am using does not offer any options such as an ignore glob, so a sin ...

Removing the year data and converting the month in JavaScript

Currently, I am utilizing the following code snippet to parse XML in Javascript: $this(find).text() When this code runs within an HTML environment, the output for the date from the XML data appears as: 2014-04-07T19:48:00 My objective is to format it l ...

Error: Property 'barcodeScanner' is not readable

Currently, I am utilizing barcodescanner.js for scanning QR codes. I have successfully downloaded and linked the CaptureActivity android library to my project. However, when attempting to execute the following code: window.plugins.barcodeScanner.scan(sca ...

Clear the input field value when the onClick event occurs, and retain the value if not changed

When I initially set a default value in the input field, it is important that this value is removed when clicked inside the field. However, if the inserted value is left blank and the mouse cursor moves away from the field, the default value must be restor ...

The Vue 2 watch feature may encounter difficulties with mixin data properties, however, it functions properly when the data property belongs to the

I recently attempted to refactor some code by moving certain functionalities to a vue mixin from the component itself, with the intention of reusing it in multiple components. The simplified version of the code looks like this: export default { data() { ...

VueJS - Building a Form Template Within a Modal Component

Struggling to include a template in a modal and unsure how to pass variables to the child template: Below is the main HTML for the application: <div id="example" class="container"> <button class="btn btn-primary" type="button" @cli ...

The unique capabilities of services and factories in Angular 1 - understanding their differences and what each excels at

After extensively combing through numerous stackoverflow posts and articles, the consensus seems to be that an angular service returns an instance, while an angular factory returns any desired object. This raises the question: what unique capabilities do ...

"Error encountered in @mui/x-data-grid's ValueGetter function due to undefined parameters being passed

I'm currently using @mui/x-data-grid version 7.3.0 and I've encountered a problem with the valueGetter function in my columns definition. The params object that should be received by the valueGetter function is showing up as undefined. Below is ...

React: Despite my efforts to return a value from render, nothing was actually returned

My current project involves creating nested components to display the dataset I have. export const MyComponent = (props) => { const groupMilestoneByYear = (data) => { // Take Milestone Data array as input and group it by Year let yearGroup ...

Avoid wrapping elements

Is there a foolproof method or best practice to prevent an HTMLElement from wrapping? Specifically, I'm referring to elements with relative positioning. One possible solution could be using absolute elements and adjusting their left position based on ...

What is the best way to toggle a specific div element within an ng-repeat loop?

I have a list of products. When I click on a product, it should be added to the database. If I click on the same product again, it should be removed from the database. I am toggling the wishlistFlag using ng-click. This works correctly for one div element, ...

Eliminate repeated elements within a JSON dataset to create a consolidated array

Looking to extract unique data from the JSON object below in order to create a result json with a list of questions and their corresponding choices. Any assistance would be greatly appreciated. Thanks in advance..!! var data = [ { "category": "s ...

The length of JSONPath in Javascript is significantly longer, approximately 3000 times lengthier than a traditional loop

I am experiencing performance issues with JSONPath implemented in JavaScript using the Stephan Goessner Library. Below is an example of the JSON structure causing the problem: [ { id:1, name: "lorem", elements: [ ...