Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda