What is the process for converting a string into a map?

Trying to transform a string from this format:

string = "John:31,Miranda:28"

To this format:

obj = { "John" => 31, "Miranda" => 28 }

I attempted to do the following:

const class = new Map();
array = string.split(",");

However, after splitting the string, I end up with something like this:

["John:31", "Miranda:28"]

I am unsure of how to convert this array into an object format (using ":" as an arrow). Is there a way to bypass using the array as an intermediary? Any suggestions would be greatly appreciated. Thank you!

Answer №1

One way to achieve this is by utilizing the split method to split the string by comma, followed by using the map function to further split the resulting strings by colon. You can then feed the array of arrays into the Map constructor.

If your intention is to have the map keyed by names:

const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => entry.split(":")));
console.log(map.get("John")); // "31" (a string)

If you prefer the numbers to be actual numbers instead of strings, you will need to convert them accordingly:

const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
    const parts = entry.split(":");
    parts[1] = +parts[1];
    return parts;
}));
console.log(map.get("John")); // 31 (a number)

You can refer to this answer for more insights on converting from string to number in JavaScript.


In case you want the map to be keyed by value instead (although it's not likely), you just need to reverse the order of entries within the inner arrays:

const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
    const [name, num] = entry.split(":");
    return [num, name];
}));
console.log(map.get("31")); // John

Answer №2

To start, divide the information based on commas and then iterate through it by separating with colons to create an object.

const data = "John:31,Miranda:28";
const myObj = data.split(',').reduce((obj, part) => {
  const pieces = part.split(':');
  obj[pieces[0]] = pieces[1];
  return obj;
}, {});

Answer №3

If you're looking to achieve a similar outcome, consider the following approach:

let information = "John:31,Miranda:28";

let splitInfo = information.split(',');

let finalResult = splitInfo.reduce((newData, individual) => {
  const [person, age] = individual.split(':');
  return {
    ...newData,
    [person]: parseInt(age)
  };
}, {});

console.log(finalResult);

Answer №4

Here's a helpful tip:

  • To start, split the string by commas and then by colons.
  • Next, combine the results into a map.

const test = "John:31,Miranda:28"; 
console.log(test);
const obj = test.split(/,/).map(item => item.split(/:/));
console.log(obj);
const _map = new Map(obj);
console.log(_map);
console.log(_map.get("John"))

https://i.sstatic.net/JzpG4.png

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

AngularJS ng-repeat items do not properly align when utilizing Bootstrap col-md-2 styles

Utilizing AngularJS ng-repeat for displaying a list of products and incorporating bootstrap col-md-2 to showcase 6 products in each row, I have included a condensed version of my code below: <!DOCTYPE html> <html lang="en"> <head> <ti ...

Can the variable name within a function be retrieved?

How can I retrieve the variable name (user_name1 or user_name2) from a sample function (GetUserName()) within itself? This variable name is required to create an object with the same name on the server side for data synchronization purposes. function GetU ...

What is the best way to decrease the border width of a chartjs doughnut chart?

I have a vision for my chart based on the mockup: However, here is what I've been able to achieve using chartjs so far: This is the code I'm working with: datasets: [ { data: [3, 8, 13, 9, 2], backgroun ...

Receive a notification when the div element stops scrolling

I am attempting to replicate Android's expandable toolbar within an Angular component. My HTML code appears as follows: <div (scroll)="someScroll($event)"> <div class="toolbar"></div> <div class="body"></div> </d ...

Troubleshooting a Numpy Array Issue: Comparing int32 and int64 for Calculations

I am puzzled by the inconsistency between the values calculated with two lines of code below. There seems to be a slight discrepancy in the calculation when using the Numpy array "load_values." Interestingly, when I replace the index with the actual value ...

Tutorial on inserting a picture into muidatatables

Important Note: The image stored in the database is called "profileImage." I am looking to create a dynamic image object similar to other objects. When I input this code: { label: "Image", name: "profileImage" }, it simply displays the image endpoint as ...

What is the best way to display a Nested JSON structure without an object key?

Need help with extracting data from two different JSON structures. The first one is straightforward, but the second is nested in multiple arrays. How can I access the content? See below for the code snippets: // First JSON { "allSuSa": [ { ...

Creating new form fields dynamically using JavaScript (triggered by onClick event)

I want to dynamically add fields based on user interaction. For instance, when the checkbox or radio button is clicked, additional fields like buttons and textfields should appear. Is it possible to achieve this using onClick? If so, can you please provide ...

Difficulty encountered in closing div by clicking the background with the help of jquery

I am facing a challenge with properly closing a div container and restoring it to its original state when I click outside of it. Despite trying various solutions from stackoverflow and extensive internet research, I have been unable to find or come up with ...

The function react.default.memo is not recognized at the createSvgIcon error

After updating my Material-UI version to 1.0.0, I encountered a peculiar error message stating that _react.default.memo is not a function at createSvgIcon Despite attempting to downgrade the react redux library to version 6.0.0 as suggested by some ...

The width of the table remains consistent

I have created a division that includes two tables stacked on top of each other. However, I am facing an issue where the width of the second table remains fixed and does not change even when I try to increase it. Here is the code snippet below: functio ...

Modify the event from creating a table on click to loading it on the page onload

Hey there, friends! I've been brainstorming and came up with an idea, but now I'm stuck trying to switch the code to onload(). I've tried numerous approaches, but none seem to be working for me. Below is the code I've been working wit ...

Sending back an HTTP response code from PHP to AJAX

I'm currently working on creating a login page for a website. The functionality involves using AJAX to send a request to a PHP script that verifies the username and password input. If the query returns a successful result, I use http_response_code(200 ...

Failure to deliver messages through socket.emit

Check out the following JavaScript code snippet: `var express = require('express'); var app = express(); var http = require('http').Server(app); var path = require("path"); var io = require('socket.io')(http); app.get(&apos ...

I'm confused why this code is functioning in JSFiddle but not on my HTML webpage

For the first time, I am encountering this issue. I am currently attempting to integrate this code into my application http://jsfiddle.net/TC6Gr/119/ My attempts include: Pasting all the jsfiddle code in a new page without my code, but it doesn't w ...

Stopping the page from refreshing on an ajax call in asp.net: a guide

Is there a way to prevent page refresh during an Ajax call? I have multiple views that open when a user clicks on a link button from a tree view. Currently, the views are refreshing the page with each button click. I would like to display a loading image ...

What is the best way to increase a specific value in an array of objects once it has been located (using findOne()), but before it is

I'm looking for a more efficient way to update an object within an array of schemas in one database request instead of two. Currently, I use findOneAndUpdate() to increment the field if the object already exists, and then I have to use update() if the ...

Mismatch between BoxGeometry and SphereGeometry alignment issue

I'm having trouble aligning spikes on a globe using sphere geometry. Despite everything else working fine, the spikes don't align properly with the globe as shown in the image below. I've tried using lookAt(new THREE.Vector3(0,0,0)) but it d ...

Is it possible to alter the appearance of my menu when clicked on?

Is there a way to update the appearance of an active menu or submenu that is selected by the user? I would like the chosen submenu and its parent menu to have a distinct style once clicked (similar to a hover effect, but permanent). /*jQuery time*/ $(do ...

Is there a way to automatically trigger a function once another function has completed its execution?

I am diving into the world of JavaScript as a beginner. All I want to do is trigger the function called seconOne() right after the execution of firstOne(). Specifically, I need the function two to be invoked when the value of p1 reaches 4. While I can us ...