I have a json file which contains json objects like following .
{
"RegionNames" : ["Region1", "Region2"],
"StageNames" : ["Stage1", "Stage2"],
"stages" : {
"Stage1" : {
"Region1" : {
"var1": "value1",
"var2": "value2"
},
"Region2" : {
"var1": "value1",
"var2": "value2"
}
},
"Stage2" : {
"Region2" : {
"var1": "value1";,
"var2": "value2";
}
}
}
}
I want to access this variable the var1 & var2 of both Region1 & Region2 in each stage .
//How i've tried accessing them in another typeScript file , the above content is in jsonContent.json : -
const stages =jsonContent.StageNames;
const regions = jsonContent.RegionNames;
for (let stageIndex in stages) {
for (let regionIndex in regions) {
console.log("Variable1 value :"+ jsonContent.stages[stageIndex].regions[regionIndex].var1)
console.log("Variable2 value :"+
jsonContent.stages[stageIndex].regions[regionIndex].var2)
}
}
Can someone please help me in this accessing in json using loop .
I need to use "RegionNames" & "StageNames" variables to run that loop , but not able to do so . Can someone please help .
1 Answer 1
You can use Object.entries() method on any object and convert it into array then use loops to access props and it's value ... Moreover I had to use forEach loop since your object isn't ideal ( meant to say that it contains something like item1 not item)..
let jsonContent = {
"RegionNames": ["Region1",
"Region2"],
"StageNames": ["Stage1",
"Stage2"],
"stages": {
"Stage1": {
"Region1": {
"var1": "value1",
"var2": "value2"
}
},
"Stage2": {
"Region2": {
"var1": "value1",
"var2": "value2"
}
}
}
};
const array = [];
Object.entries(jsonContent.stages).forEach(entry=> array.push(entry[1]));
array.forEach((item, index)=>{
index++;
const region = 'Region'+ index;
const object = item[region];
// console.log(object)
console.log("Variable1 value :"+ object.var1);
console.log("Variable2 value :"+ object.var2);
});
Note : you should never use indexes inside object like item1 as in objects of same data structure it is recommended to store data in easy way not using indexes with....
4 Comments
Region1 could have been written as Region only ...
let var = {means that it's not JSON. It also has syntax errors.