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

128
Visualizações
Convert the string to an object

I want to convert a string to an object.

My string is something like 7541550448872:1:1:monthly,42397357179112:1.

I want the result to be something like this:

'items': [{
    'id': 7541550448872,
    'quantity': 1,
    "properties": {
      "shipping_interval_unit_type": "monthly",
      "shipping_interval_frequency": "1"
    },
  },
  {
    'id': 42397357179112,
    'quantity': 1,
  }
]

I was told to use functions like split() and Regex but I could not get it to work. Any idea how to do this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For me, probably the most preferred method is using Array.split(). You split the array by :, and then construct the JSON by indexing the array. See the code snippet below to see this in action. Also, I'm not sure if you wanted a , between the month and the id or if was just a typo. My code below uses the ,.

const str = '7541550448872:1:1:monthly,42397357179112:1';
const arr = str.split(':');
const json = {
  'items': [{
      'id': Number(arr[0]),
      'quantity': Number(arr[1]),
      "properties": {
        "shipping_interval_unit_type": arr[3].split(',')[0],
        "shipping_interval_frequency": arr[2]
      },
    },
    {
      'id': Number(arr[3].split(',')[1]),
      'quantity': Number(arr[4]),
    }
  ]
};

console.log(json);

Hoped this helped!

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