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"
}
]
}
]
}
CodePudding user response:
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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
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