The most efficient method to obtain the accurate value

I'm currently facing an issue with extracting a value from a JSON object. Each JSON object in my array has a name (attribute), a similarity (ignore this for now), and an array named "values" with keys and corresponding values.

For each case, I have a value from this array, as shown in the example below. My goal is to retrieve the value from "Values" using the key specified in my case.

Currently, I am using two nested loops, one to find the correct attribute and another to find the right key. Is there a more efficient way to achieve this? If necessary, I can restructure this JSON schema.

Here is my array:

[
  {
    "attribute": "date",
    "similarity": "Sim",
    "values": [
      {"key": "Unknown", "value": "?"},
      {"key": "April", "value": "0"},
      {"key": "May", "value": "1"},
      {"key": "June", "value": "2"},
      {"key": "July", "value": "3"},
      {"key": "August", "value": "4"},
      {"key": "September", "value": "5"},
      {"key": "October", "value": "6"}
    ]
  },
  ...
]

A sample case:

{
    "case": 1,
    "disease": "diaporthe-stem-canker",
    "areaDamaged": "low-areas",
    "cankerLesion": "Brown",
    ...
  }

In the case where "areaDamaged" is set to "low-areas," I want to extract the corresponding value associated with "low-areas." Does anyone know a better approach?

Answer №1

When considering what is "better," I assume you are referring to efficiency.

In that case, if arrays are present everywhere in your code, there may not be a more "efficient" option available.

However, if your arrays contain reference data that will be accessed repeatedly, one approach could be to convert the arrays into maps for improved performance. Here's an example:

var refDataMap = {};

var refDataItem, refDataValue;

for (var i = 0; i < refData.length; i++) {
    refDataItem = refData[i];
    refDataMap[refDataItem.attribute] = refDataItem;
    refDataItem.valuesMap = {};
    for (var j = 0; j < refDataItem.values.length; j++) {
        refDataValue = refDataItem.values[j];
        refDataItem.valuesMap[refDataValue.key] = refDataValue.value;
    }
}

var result = refDataMap["seed"].valuesMap["Abnorm"]; // Returns value 1

Performance tests have shown that accessing a map like this is approximately 25% faster than iterating over arrays ().

However, if the map initialization sequence is included in the test, then arrays are twice as fast when measured for a single access ().

Based on observations, it seems that you would need to access this data around 50 times for the overhead of map initialization to become beneficial ().

Answer №2

Instead of including the properties "valor" and "chave" within the json file, you have the option to directly use key/value pairs in the json structure.

For example:

var attributes = {    
    "areaDamaged" : {
        "similarity": "Same",
        "values": {
             "Unknown" : "?",
             "scattered" : "0",
             "low-areas" : "1",
             "upper-areas" : "2",
             "whole-field" : "3"
         }
    },
 ...

As a result, retrieving the value becomes simpler:

var value = attributes["areaDamaged"].values["low-areas"];

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

The Mean Stack by Bitnami

After setting up the Mean Stack Manager, I encountered an issue. When running a command in the node terminal like console.log("Hello World"), it runs smoothly. However, if I place a Javascript sample file in any folder within the mean stack install directo ...

Leveraging ES6 modules within JavaScript for exporting uncomplicated variables

In my JavaScript code, I have defined pageId = 3 in one file and socket = io() in another file. Now, I need to access these variables in other files. I am considering using ES6 modules for this purpose, but I am unsure of how to proceed. Currently, the s ...

Efficiently Encoding Still Image Data for NextJS

Currently, I am experimenting with a completely static method in my new Next.js v12 project. I am creating 5-6 data files to use with getStaticProps. Here is an example of one of the data file structures (they are all similar): import SqAshland1 from &apos ...

Displaying JSON data using Jquery

I am currently trying to fetch a JSON response and display it in a div ... I have written a script for the same script $('select#mes').on('change',function(){ var valor = $(this).val(); var route = "http://localhost/UJOBB/ ...

How can I load 3-D models in three.js by specifying file content instead of the file path?

I'm looking to develop an interactive online model viewer that allows users to easily upload and view models without having to manually edit the source code. Unfortunately, most browsers restrict access to file paths, but can still read file contents. ...

DataFrame conversion from JSON file resulted in a ValueError: Encountered an unexpected character while decoding an array value (2)

I am dealing with a large JSON file that follows this structure: [{"faceId": "2cb5a26a-1acc-4eb2-8c39-8e05e604f057", "faceRectangle": {"top": 54, "left": 125, "width": 78, "height": 78}, "faceAttributes": {"smile": 0.584, "headPose": {"pitch": 0.0, "rol ...

receiving a drop event following a drag leave in HTML5

When participating in HTML5 DnD events to receive files dragged from the desktop, I have encountered an issue where I always receive a dragleave event just before the drop event. This behavior is not mentioned in the specification, and if one uses the drag ...

Displaying a dialog or popup in React Native when catching errors

Exploring React Native has been quite a journey for me, especially when trying to implement a popup for error handling. Despite numerous attempts, I haven't been successful in getting it to work as desired. The code snippet below captures my current i ...

Creating Vue components and including Javascript code within them

Attempting to develop a component using Vue for my JavaScript code, but encountering issues. My primary aim is to build a component with either Vue or Vue3 <head> <title></title> <script src="https://cdn.jsdelivr ...

highlight the selected option in the ng-repeat list of items

Looking for some assistance with a coding problem I'm having. I keep running into an error when trying to make a selected item in an ng-repeat list highlight. The CSS style is only applied on the second click, not the first. Additionally, I need to en ...

"Building a dynamic form with ReactJS, Redux Form, and Material UI - Implementing an

Currently working on a nested form framework that utilizes the redux form and material UI framework. The components have been developed up to this point - https://codesandbox.io/s/bold-sunset-uc4t5 My goal is to incorporate an autocomplete field into the ...

No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location. location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true ...

What are the best techniques for using jQuery to manipulate an HTML form that contains nested elements?

I have a scenario where I need to dynamically generate mini-forms within an empty form based on certain conditions. For instance, imagine a form that gathers information about restaurants such as their names and locations. Depending on the number of restau ...

What might be the reason why my form doesn't seem to be recognizing the submit() function in

Being new to asp.net and javascript, I am struggling to find helpful web resources and troubleshoot javascript errors. The specific issue I'm facing is with the line oFormObject.submit(); which throws a Microsoft JScript runtime error: Object doesn&a ...

Exploring the World of JSON File Parsing in Unity line by line

{ "Recipes": [ { "Tag": "Salad", "Ingredients": [ "Tomato", "Olive oil", "Thyme", "Lemon", "Black Pepper", ...

Array of arrays of pointers to a struct array in two dimensions

In my code, I have 3 arrays that are structured as follows: typedef struct heapMemNode { int *coord; int x, y; int *prevcoord; int px, py; int d; char tp; int *telcoord; int c; } hmemn; hmemn *heapmem = calloc((siz2+1), si ...

Viewing a Google Charts graph upon the loading of a web page

Utilizing the Google Charts library, I have incorporated a graphic on my web page that is dynamically added using AJAX into a <div> element. To display the graph when the page loads, I have written the following code: <script type="text/ ...

Jquery button click event is malfunctioning after the inclusion of jquery keyboard plugin

When I try to gather user input from a textbox using jQuery keyboard.js, the functionality works perfectly fine if I exclude the virtual keyboard code. For more information on keyboard.js, you can visit: https://github.com/Mottie/Keyboard/wiki Below is t ...

Updating the logic for reconnection when the connection is closed in MySql's X DevAPI can be achieved by utilizing the @mysql/xdevapi module

I am currently utilizing the X DevAPI of MySql v8.0.33 with the @mysql/xdevapi v8.0.33 package. Although I have implemented a reconnect logic, it doesn't seem to be functioning as expected. Here is the code snippet: const mysqlx = require('@mysq ...

Having trouble with your HTML5 canvas?

Below is the JS code snippet: function DisplayText(output, x, y){ var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillText ("A" , x, y); ctx.font = 'bold 20px sans-serif'; ...