Obtain the value from an array where the key is another array that contains a key-value pair

I have code that performs calculations by looking up values in my array of arrays using keys. Here is what I am trying to achieve:

For example, if the score value is 1, I want to retrieve key 1 from the array. There is also a second parameter we can call total. From key 1, we need to find the total within the array and its corresponding value.

It would look something like this: Score = 1 Total = 4 Value = ?

array 1:[1:3,2:6,3:19,4:55];

Therefore, the expected result should be the value 55.

var scores =[{1:[{value:'4'},{score:'1'},{css:'green'}]}];

I have only used one key in the outer array for simplicity.

In order to see how this works, I implemented a loop:

for (var key in scores){
    console.log(scores[key]);
    var arr = scores[key];
    for (var value in arr){
        console.log(arr[value]);
        var single = arr[value];
        for(var val in single){
            console.log(single[val]);
        }
    }
}

The final loop displays the inner array with keys and values as objects.

Now, I am contemplating the best and most efficient way to retrieve these values, especially when performing an operation like:

function getValue(Score, Total){
    alert("Key " + value + "is " + this); 
    alert("Key " + score + "is " + this); 
    alert("Key " + css + "is " + this); 
}

Thank you.

Answer №1

Why make it so complicated? Simplify things with code like this:

var data = [
    {'number': 7, 'color': 'blue'}, // This is index 0
    {'number': 3, 'color': 'red'} // This is index 1 and so on
];

function getDataValue( index, property ) {
    return data[index][property];
}

// Example:

console.log(  getDataValue(1, "color") ); // red

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

Encountered an error in Discord.js: Undefined properties unable to be read (execute)

Here is the code snippet from my main file: const { Client, IntentsBitField, Collection, intents, SlashCommandBuilder } = require('discord.js') const { TOKEN, PREFIX } = require('./config.json') const fs = require('fs'); const ...

Using a for loop to iterate through a JSON object in JavaScript

As a beginner in JS, I am attempting to iterate through the given JSON data: myLogger - myLogger - JSON ARRAY - {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distan ...

notifying with JQuery when a cookie is about to expire

Utilizing cookies, I am attempting to display an alert message and a blinking status message indicating that the cookie is about to expire in a countdown style. Users will have 60 seconds to click on a link to extend the expiration time. If they do not cli ...

Comparing the architecture of two JSON objects in JavaScript without taking into account their actual content

One of the tools I rely on for my projects is a Node.js based mock server that helps me specify and mock API responses from the backend. However, it would be beneficial to have a way to ensure both the backend and frontend are in sync with the specified st ...

Troubleshooting problem with rotation and text geometry label on AxisHelper

Within my main scene, there is a sphere along with a subwindow located in the bottom right corner where I have displayed the (x,y,z) axis of the main scene. In this specific subwindow, I am aiming to label each axis as "X", "Y", and "Z" at the end of each ...

Guide on converting JSON data into a PDF using TypeScript

I need to take JSON data and convert it into a PDF format when the PDF button is clicked in the UI. I have tried a few things but I'm struggling with binding the response to the PDF function. My goal is to display values from the "actualExpenses" arra ...

Order a array of JSON by time, showing it in a 12-hour format

I've come across a JSON structure that looks like this: [ { "Event_code": "AB-001", "Start_time": "11:00 AM", "End_time": "3:00 PM", "Session_type": "Tour" }, { "Event_code": "AB-002", "Start_time": "09:30 AM", "End_ ...

The function url_for is failing to interpret the variables I am passing to

My goal is to allow users to upload images that are then displayed to all users. The variable "Data" holds the file name (e.g., "files/dog.png"). However, when I try to set the newImg.src value as "{{url_for('static', filename = data )}}", it onl ...

Tips for maintaining the particles.js interaction while ensuring it stays under other elements

I have incorporated particle.js as a background element. By adjusting the z-index, I successfully positioned it in the background. While exploring solutions on the Github issues page, I came across a suggestion involving the z-index and this code snippet: ...

I am puzzled by the issue with my logic - the button only changes once and then the onclick function ceases to work

I am having an issue with a button that should switch between displaying temperatures in Fahrenheit and Celsius when clicked. It works for the first two clicks, but on the third click, it stops working even though I've set the class back to .temp. $( ...

What is the method for retrieving the title element from the Json data?

I am attempting to extract JSON data from http://omadbapi.com/?s= for a search script, but I am encountering difficulties in retrieving the Title element from this particular JSON: { "Search": [{ "Title": "Sherlock Holmes: A Game of Shadows", ...

How to save data to a JSON file using the filesystem module in Node.js

After coming across this helpful guide at , I was intrigued by the creation of a point system in discord.js. The use of let points = JSON.parse(fs.readFileSync("./points.json", "utf8")); to read the file piqued my interest, leading me to explore how to bui ...

Raising the css value for each element that is impacted

I am faced with an infinite number of elements that I need to arrange next to each other. Each element has a class called "box". My goal is to separate each box by 10px increments, meaning the first element will have a left property of 0px, the second 10px ...

How can I utilize the LED flash on a Windows Phone using WinJS?

Currently delving into the world of WinJS and endeavoring to create an application that involves operating the LED Flash. I am seeking guidance on how to properly access the LED Flash functionality to allow for toggling it ON or OFF. Your insights on how ...

Ways to display a horizontal grid

Is there a way to display the grid in an ASP page horizontally with a page size of 3? Are there any properties of the grid that can help achieve this horizontal layout? I have tried using properties like AlternatingRowStyle-HorizontalAlign and EditRowStyle ...

What is the best way to save data from an ng-repeat array in MEANJS?

I've been exploring MEANJS at meanjs.org and I'm having trouble storing array data for ng-repeat in the deal object, which includes dealtype and dealprice. Despite setting up addFields for the ng-repeat input tag in the create form, the data isn& ...

Changing marker colors dynamically in Google Maps with NextJS

I'm using the @googlemaps/js-api-loader package to load a map in my nextJS app. I have a list of locations that I want to plot on the map, and I also want these locations disabled on the left side of the page. When hovering over one of the locations ...

What makes realtime web programming so fascinating?

Working as a web developer, I have successfully created various real-time collaborative services such as a chat platform by utilizing third-party tools like Redis and Pusher. These services offer straightforward APIs that enable me to establish bidirection ...

Incorrect Matching with Regular Expressions

I'm working on a regular expression to validate a URL. var url = "https://www,google.com"; var urlRegex = /(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&@#\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&@# ...

FixPermissions not working properly | Discord.js EXPERT

I am currently in the process of updating my bot to be compatible with the latest version of discord.js. I have successfully made various changes, but I am facing an issue with the overwritePermissions section within my ticket command. For some reason, the ...