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

196
Visualizações
How to convert an array of string into a Javascript object?

Each user's information is separated by a comma, or a space, but some pieces of information can be blank. I'm looking for a solution to take the user information and create an object (key-value mapping). Here's my approach, but I can't get multiple objects.

function Person(name, email, age, occupation) {
  this.name = name;
  this.email = email;
  this.age = age;
  this.occupation = occupation;
}

let string = "Norbert,norbert@test.com,51,Coder Noemi,,,Teacher Rachel,rachel@test.com,,"
let stringArr = string.split(/[\s,]+/)

const personObj = new Person(...stringArr)

console.log(personObj)

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

0

When splitting the string, you need to keep the empty strings between the commas, but you are splitting sequences of commas as one divider - [\s,]+.

Split the string by a single , or a sequence of spaces - /,|\s+/. Then create an array of Person using Array.from(), dividing the original length by 4, and taking 4 properties by slicing the original array:

function Person(name, email, age, occupation) {
  this.name = name;
  this.email = email;
  this.age = age;
  this.occupation = occupation;
}

const string = "Norbert,norbert@test.com,51,Coder Noemi,,,Teacher Rachel,rachel@test.com,,"
const stringArr = string.split(/,|\s+/)

const personArr = Array.from({ length: stringArr.length / 4 }, (_,i) => 
  new Person(...stringArr.slice(i * 4, i * 4 + 4))
)

console.log(personArr)

about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming space is a line separator, and comma is a field separator, split:

function Person(name, email, age, occupation) {
  this.name = name;
  this.email = email;
  this.age = age;
  this.occupation = occupation;
}

let string = "Norbert,norbert@test.com,51,Coder Noemi,,,Teacher Rachel,rachel@test.com,,";

const persons = string.split(' ').map(r => new Person(...r.split(',')));

console.log(persons)

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