Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

70
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!