Home > Software design >  Get the value of a variable that is called the same as a property of the JSON
Get the value of a variable that is called the same as a property of the JSON

Time:12-02

I have a project in Typescript where I am trying to get the value of a variable with the same name as a property of a JSON object.

This is my JOSN:

let titleSheets = [
  {
     "properties":{
        "title":"totalAtm"
     }
  },
  {
     "properties":{
        "title":"totalWor"
     }
  }
];

These are my variables:

let totalSer: number = 917,
    totalWor: number = 7237,
    totalAtm: number = 1410,
    totalCt: number = 1039,
    totalSt: number = 27

This is what I am doing:

let totalAll: Array<number>
for (let title of titleSheets) {
  //console.log([title.properties.title])
}

This is what I want to get:

totalAll = [1410, 7237]

CodePudding user response:

I'm not 100% sure what you want to achieve, but you can use a variable to get an attribute of an object. In your case, you could do something like this:

// Create an object with your numbers to extract numbers dynamically via variables
const theNumbers = {
  totalSer: 917,
  totalWor: 7237,
  totalAtm: 1410,
  totalCt: 1039,
  totalSt: 27
}

// Get numbers of the object using the properties defined in "titleSheet":
const totalAtm = yourNumbers[titleSheets[0].properties.title];
const totalWor = yourNumbers[titleSheets[1].properties.title];

// Combine into array
const totalAll = [totalAtm, totalWor]

CodePudding user response:

While your properties are well defined, I propose this solution:

let titleSheets = [
 {
  "properties":{
    "title":"totalAtm"
   }
 },
 {
  "properties":{
     "title":"totalWor"
  }
 }
];
//These are my variables:

let totalSer: number = 917;
let totalWor: number = 7237;
let totalAtm: number = 1410;
let totalCt: number = 1039;
let totalSt: number = 27;
//This is what I am doing:

let totalAll: Array<number>= [];
for (let title of titleSheets) {
  switch(title.properties.title){
    case "totalSer": 
      totalAll.push(totalSer);
      break;
    case "totalWor": 
      totalAll.push(totalWor);
      break;
    case "totalAtm": 
      totalAll.push(totalAtm);
      break;
    case "totalCt": 
      totalAll.push(totalCt);
      break;
    case "totalSt": 
      totalAll.push(totalSt);
      break;
    default:
      console.log(`Sorry, we are out of ${title.properties.title}.`);
 }

}

console.log(totalAll);
  • Related