Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda