Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
How do I convert a string to a dictionary in javascript?

I have a string

var str = "1:6,5,2,2:3";

I want to convert this str into a js dictionary such that:

var dict = {1:"6,5,2",
            2:"3"};

so that I can fetch the values by their respective key index. How do I convert it?

I had tried this code to store the splitted values into an array:

var pages = "1:6,5,2,2:3";
var numbers = [];
if (pages.includes(',')) {
  page_nos = pages.split(',');
  for (var i = 0; i < page_nos.length; i++) {
    if (page_nos[i].includes(':')) {
      var n = page_nos[i].split(':');
      numbers.push(n[1]);
    } else {
      numbers.push(page_nos[i]);
    }
  }
} else {
  page_nos = pages.split(':');
  numbers.push(page_nos[1])
};

console.log('numbers: ', numbers);

But it's incorrect, as without dictionary it's impossible to know what value belongs to which index

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

If you cannot make your input string a proper JSON or another easily parsable format in the first place, this answers your question:

const str = "1:6,5,2,2:3";

const obj = str.split(/,(?=\d+:)/).reduce((accu, part) => {
  const [k, v] = part.split(':', 2);
  accu[k] = v;
  return accu;
}, {});
console.log(obj);

Cut the string at all commas that are followed by digits and a colon. Each part has a key in front of a colon and a value after it, which should be stuffed in an object in this format.

about 4 years ago · Juan Pablo Isaza Report

0

No mutations solution.

const str = "1:6,5,2,2:3";

const dict = str
  .split(/(\d+:.*)(?=\d+:)/g)
  .reduce((t, c) => {
    const [key, value] = c.replace(/,$/, "").split(/:/);
    return { ...t, [key]: value }
  });

  
console.log(dict);

about 4 years ago · Juan Pablo Isaza Report

0

if you consider not using regular expression, you might try this as well. to take out a dict (Object) from that string, this will do.

var pages = "1:6,5,2,2:3";

function stringToObject(str) {
    
  var page_object = {};

  var last_object;

  str.split(",").forEach((item) => {
    if (item.includes(":")) {
      page_object[item.split(":")[0]] = item.split(":")[1];

      last_object = item.split(":")[0];
    } else {
      page_object[last_object] += `,${item}`;
    }
  });
  return page_object;
}

console.log(stringToObject(pages))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!