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

74
Visualizações
Populate JSON with multiple string variables

I have simplified what I'm presenting here, but I'm having some trouble "populating" a JSON structure with these 3 variables. I can't figure out how to create new objects and I end up storing all of name, age or state in 1 object. I'm using nodeJS, any tips would be appreciated.

const name = "Jason" + '\n' + "Freddy" + '\n' + "Chucky"
const age = "31" + '\n' + "25" + '\n' + "15"
const state = "CA" + '\n' + "NY" + '\n' + "PA"

console output will show this

Jason
Freddy
Chucky
31
25
15
CA
NY
PA

I want to take those values from the 3 variables and create this...

{
    "overview": 
    [
        {
            "people": 
            [
                {
                    "name": "Jason",
                    "age": "31",
                    "state": "CA"
                },
                {
                    "name": "Freddy",
                    "age": "25",
                    "state": "NY"
                },
                {
                    "name": "Chucky",
                    "age": "15",
                    "state": "PA"
                }
                
            ]
        }
    ]
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First, parse the initial data using split.

After that, create the structure you wish and then iterate through your data and populate the people array using push method.

const name = "Jason" + '\n' + "Freddy" + '\n' + "Chucky";
const age = "31" + '\n' + "25" + '\n' + "15";
const state = "CA" + '\n' + "NY" + '\n' + "PA";

const names = name.split('\n');
const ages = age.split('\n');
const states = state.split('\n');

const obj = { overview : [
  {
    people: []
  }
]}

for (var i = 0; i <= 2; i++){
   const person = {};
   person.name = names[i];
   person.age = ages[i];
   person.state = states[i];
   obj.overview[0].people.push(person);
}

console.log(obj);

push - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

split - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

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