2

I need to turn a string formatted like that:

string = "John:31,Miranda:28"

Onto this;

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

I did this :

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

And obviously I do not know what do with it because after the split I get something like this:

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

And I don't know how to turn it onto an object (using the ":" as a arrow)... Maybe I don't need to use the array as an intermediary? Any thoughts? Thanks

4 Answers4

3

You can use split to split by comma, and then map on the resulting strings to split again by colon, and feed the resulting array of arrays into the Map constructor.

For instance, if you want the map keyed by the names, which I suspect you do:

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 want the numbers to be numbers, not strings, you'll need to convert them:

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)

My answer here goes into some detail on your options for converting from string to number.


If you want the map keyed by value instead (which I suspect you don't, but...), you just have to reverse the order of the inner array entries:

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
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You could try something like this:

const data = "John:31,Miranda:28"

const splitData = data.split(',')

const result = splitData.reduce((newObject, item) => {
  const [name, age] = item.split(':')
  return {
    ...newObject,
    [name]: parseInt(age)
  }
}, {})

console.log(result)
Joss Classey
  • 1,054
  • 1
  • 7
  • 22
0

So split on the commas, loop over it and split on the colon, and build the object.

var myString = "John:31,Miranda:28"
var myObj = myString.split(',').reduce(function (obj, part) {
  var pieces = part.split(':')
  obj[pieces[0]] = pieces[1]
  return obj
}, {})
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

I'll just add this here:

  • Basically, split string by the comma, then the colon.
  • Combine result 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"))

enter image description here

Murwa
  • 2,238
  • 1
  • 20
  • 21