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

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

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 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