Retrieve the value of a variable with the exact same name as a key in the JSON object

I am currently working on a Typescript project where I need to extract the value of a variable with the same name as a property in a JSON object.

Here is an example of my JSON data:

let assets = [
  {
     "properties":{
        "title":"totalCars"
     }
  },
  {
     "properties":{
        "title":"totalBikes"
     }
  }
];

These are some sample variables that I have:

let totalHomes: number = 235,
    totalBikes: number = 56,
    totalCars: number = 127,
    totalBoats: number = 19,
    totalTrucks: number = 8

This is what I am trying to achieve:

let vehicleCounts: Array<number>
for (let asset of assets) {
  // extracting the value from the corresponding property in the JSON object
}

The desired outcome would be:

vehicleCounts = [127, 56]

Answer №1

Although your properties are clearly defined, I suggest the following approach:

const sheetsList = [
 {
  "properties":{
    "title":"totalAtm"
   }
 },
 {
  "properties":{
     "title":"totalWor"
  }
 }
];
//Defined variables:

let totalService: number = 917;
let totalWork: number = 7237;
let totalAtmosphere: number = 1410;
let totalCount: number = 1039;
let totalStatus: number = 27;
//Implementation logic:

let allTotals: Array<number>= [];
for (let sheet of sheetsList) {
  switch(sheet.properties.title){
    case "totalService": 
      allTotals.push(totalService);
      break;
    case "totalWork": 
      allTotals.push(totalWork);
      break;
    case "totalAtmosphere": 
      allTotals.push(totalAtmosphere);
      break;
    case "totalCount": 
      allTotals.push(totalCount);
      break;
    case "totalStatus": 
      allTotals.push(totalStatus);
      break;
    default:
      console.log(`Apologies, we have run out of ${sheet.properties.title}.`);
 }

}

console.log(allTotals);

Answer №2

If you're not entirely sure about your goal, one approach could be to utilize a variable to access an attribute of an object. In this scenario, consider following this pattern:

// Define an object containing the numbers you need
const numberObject = {
  totalSer: 917,
  totalWor: 7237,
  totalAtm: 1410,
  totalCt: 1039,
  totalSt: 27
}

// Access the numbers within the object using the titles from the "titleSheets":
const totalAtm = numberObject[titleSheets[0].properties.title];
const totalWor = numberObject[titleSheets[1].properties.title];

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

If you wish to iterate over all variables in the JSON data, you can adapt the previous method by incorporating a loop:

const totalAll = new Array<number>();

for (let titleSheet of titleSheets) {
  const number = numberObject[titleSheet.properties.title];
  totalAll.push(number);
}

For a minimal demonstration, you can view it in StackBlitz here: https://stackblitz.com/edit/typescript-lnrkns?file=index.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble encountered with Angular Google Maps integration when using router-outlet

Currently, I am in the process of developing an application that features a map as its header (providing a global view) and another map positioned in the center of the page to showcase detailed views. To demonstrate this setup, I have shared a working exam ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

Import data from an external JSON file

I'm having trouble retrieving JSON data from an external file. Oddly enough, it works perfectly when I include the JSON inline. However, after creating a file named test.json and transferring the JSON content into it, I can't seem to access the i ...

Sort array in ReactJS using JSON data fetched from a URL

There is a URL where I have stored some data, such as: [ {"id":1,"first_name":"add","last_name":"add"}, {"id":2,"first_name":"sfdf","last_name":"aad"} ...

Learn the process of showcasing HTML content containing images within a JSON file using ReactJS

The image from an external source is displaying correctly. I am trying to showcase HTML content with the following image: <img src='https://localhost:3000/static/media/image.jpg' alt='tutorial' /> which is located in my src folder ...

What is the process for invoking a service from a component?

I'm currently facing an issue with my service that is responsible for making HTTP requests and returning responses. The problem arises when I try to display parts of the response on the screen within my component, as nothing seems to be showing up des ...

Ways to determine if an optional parameter has been defined

One method I use to verify if the body property has been passed to the function. Is there a more straightforward approach in TypeScript? httpAPI<T>(httpMethod: HttpMethod, url: string, optional?: { params?: HttpParams, body?: any, isUseCache?:boole ...

Can you explain the meaning of { [key: string]: boolean; } data type?

Have you come across this function declaration recently? static required(control: AbstractControl): { [key: string]: boolean; }; What does the return value of this function mean? It seems to be returning an object with multiple properties, each c ...

What is the method for retrieving this data using Javascript?

I received this JSON-encoded data: { "error": { "msg":"Concurrent verifications to the same number are not allowed", "code":10 } } and I tried to access the 'msg' value using JavaScript as follows: $("#buttonPhoneSubmit ...

Struggling to organize data into a hierarchy using the D3.js nest function

Attempting to build a d3.js tree, I need my data to be in hierarchical form before using d3.treeLayout. Currently, here is what my json array looks like: var data = [ {"group":"1","price":"36599.88", "cy":"44260"}, {"group":"2","price":"36599 ...

No content appearing instead of AngularJS code displayed

My goal is to retrieve data from a MySQL database using PHP and then pass that data in JSON format to AngularJS for display in a table. The HTML code looks like this: <body ng-app="myModule"> <div class="row"> <div class="col-lg-12 ...

Prompt user to save changes or cancel before closing modal (if closed by pressing ESC or clicking the backdrop)

When I manually close the modal, everything works fine. I just create a prompt and only call the BsModalRef.hide() method when the prompt (sweetalert) is closed. However, when the modal is closed using the ESC key or click-outside events provided by Boots ...

Retrieve information from a JSON array in AngularJS using an ID

I am currently utilizing a JSON file to store information about all the individuals in my database. This data is being used to display first and last names on a web page, and I now want to incorporate the ability to view detailed information about each per ...

Updating an individual item from an array of objects using ReactJS

I am facing an issue with my database's Opening Time table. Whenever I try to modify the opening time of one day, the opening time of other days gets deleted as well. Below is the code snippet I'm using to update my state data: async handleCha ...

Browser with Node's https.Agent

In my npm package written in TypeScript, I utilize axios to make web requests. One of the endpoints requires certificate authentication, so I pass new https.Agent to axios to include the necessary certificates. Everything works perfectly when the module is ...

Why am I unable to utilize an array in this manner in JavaScript, and what is the method for accessing the array using a calculated number?

var nodesXY = ['15% 15%','30% 16%','19% 42%','39% 80%',]; var number = ["0","1","2","3","4","0","0","0"]; //some loop AccesNodes(number[1]); function AccesNodes(number){ console.log(number); // ...

Tips on effectively parsing a JSON string in a React Native application

I stored all the information in asyncStorage as a string, and then attempted to parse it. When I check the console log, this is what I see: "{\"metadata\":{\"lastSignInTime\":1610728860334,\"creationT ...

Using Javascript to populate a dropdown menu from a JSON file and show it in a container

After following a tutorial, I successfully created my own space invaders game. However, I am now facing a challenge in populating a select list of states using JSON within the JavaScript code. I have set up the necessary elements to display the select box ...

Building an Angular 4 app featuring a customized default landing page and URL parameters functionality

I am in the process of developing a web portal that will be embedded within an iFrame. Below is the code snippet I am using to set up the portal: Routes Configuration const routes: Routes = [ { path: '', redirectTo: '/dash ...

Generating custom error messages with specified format when utilizing routing-controllers

I'm currently working on a Node APP that utilizes the routing-controllers library. In the README file, there is a section titled Throw HTTP errors, which includes a self-explanatory example. However, I encountered an issue when attempting to replicat ...