What is the best way to alter a key within a for loop in real time?

I am looking to dynamically change the key in a for loop. To better explain my needs, I have created a demo using the playground from this link.

My requirement is to be able to switch keys based on certain logic, as the keys in the array data may vary depending on the JSON feed. Therefore, hard coding the keys is not feasible.

Thank you in advance.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p id="demo"></p>

<script>

var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo", 
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford", 
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi", 
"colour":"silver"}];

var text = "";
var i;
for (i = 0; i < cars.length; i++) {

var keyToChoose = "name"; /// or I could choose "colour"

text += cars[i][keyToChoose] + "<br>";  /// how do I dynamically change 'keyToChoose'?

}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Answer №1

This is the correct way to utilize it.

result += vehicles[index][attribute] + "<br>";

The outcome varies based on the content of keyToChoose variable.

Answer №2

To determine the key, you have the option of utilizing a global variable.

<script>

// 1 = category , 2 = type
var selectedKey = 1;

var items = [{"category":"Electronics", "type":"Laptop"}, {"category":"Clothing", 
"type":"Shoes"}, {"category":"Food", "type":"Fruit"}];

var output = "";
var index;
for (index = 0; index < items.length; index++) {

// The choice of key is controlled by the selectedKey which can be modified as a global variable.
var chosenKey = selectedKey === 1 ? "category" : "type";

output += items[index].chosenKey + "<br>"; /// Is there a way to dynamically adjust 'chosenKey'?

}
document.getElementById("result").innerHTML = output;
</script>

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

Having trouble rendering the React app; encountered an error: JSX contents are unterminated

I am currently facing an issue while trying to fetch data from an API in React using Axios. How can I ensure that useEffect functions properly? My objective is to create a page by fetching data from an API in React through Axios. I have designed a compon ...

Dividing a string into three separate arrays

When data is received from a serial port, it often comprises multiple values separated by a semicolon. For instance: 10;155.4587;0.01 The challenge lies in extracting these values and adding them to a Listview box. While the Split(';') function ...

Setting header details for optimal data transfer

Currently, there is a Java code snippet that I am working on which attempts to access the header information sent by an HTML page. Unfortunately, I do not currently have the specific HTML page in question. However, I still need to be able to access and m ...

Material appears abnormally shiny and reflective

I've been working on rendering an object with materials using Three.js, but I've noticed that the final result looks different from what I see in other online viewers, such as , which also utilizes Three.js under the hood. I've attempted to ...

I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronolog ...

Is it possible to validate my form using only class?

I have a group of radio buttons with the same class. These radio buttons are dynamic, which is why I am considering using the class for validation. Below is my code snippet: $('#listening_choices_wrapper').on('submit', function(e) ...

Implement a function that returns JSON elements in PHP, each separated by commas

Is there a way in PHP to retrieve JSON elements values and concatenate them into a string with commas? This is my approach to fetching the "list" JSON file in PHP: $list = file_get_contents('http://example.com/list/json'); $items = json_decode( ...

Difficulty encountered when using `require('bignumber.js')` in Truffle test, despite successful installation as shown by `npm ls -g` (Windows)

While exploring solidity code testing with truffle, I encountered the need to work with BigNumber values returned from or sent to contracts and decided to include the appropriate library. My current test consists of just one line: let BigNumber = require(& ...

What is the best way to manage the input mask?

I am working with an API that provides input masks based on country codes. My goal now is to create a function that will dynamically format the input as the user types. For instance, if the user selects country code +55 and I receive the mask (##)####-### ...

Issues arising with VueJS array props when integrating Bootstrap

I am attempting to display two divs next to each other while iterating through props (which are essentially an array) in VueJS. When I have just a single element, everything functions properly. However, as soon as I include the v-for directive, the element ...

A valid path is required in the form of a string when working with the HTTP module in Node.js

Currently, I'm working on an update checker that doesn't involve downloading the update. My main goal is to compare the version in the package.json file on GitHub with the one in my Electron app. However, when using this code, I encountered a "p ...

The functionality of the click and mousedown events seems to be disabled when using an Ajax form

Trying to create a simple Ajax popup featuring a form with 3 data fields and a submit button, however I'm unable to trigger the submit button programmatically. jQuery('#FormSubmit').click() seems to have no effect. The same goes for jQuer ...

What is the correct way to properly install leaflet using npm?

I encountered an issue while attempting to install the leaflet library on npm. Despite trying various troubleshooting steps such as reinstalling npm, clearing cache, removing node_modules, and retrying the installation, the error persists. nasersobhan@Nase ...

The Ajax request is not functioning as expected

Recently, I've been experimenting with AJAX for the first time and facing some challenges in getting it to work properly. In my view file (vueConsigne.php), I have a table that is generated by my controller. <tbody> <?php echo $tab_p ...

Prevent Copying and Pasting within the Text Editor

@if (Model.CanMaintainNcrLineManagement) { <tr> <td>@Html.TextAreaFor(model => model.Description, new { id = "txArNcrLineDescriptionValue", @style = "height:520px" })</td> </tr> } else { <tr class="read-only-editor"> &l ...

The issue persists with the ajax.reload() function in DataTables

It's been driving me crazy that my datatables table won't refresh, despite using ajax.reload. I've spent weeks on this code but still can't get it to work. DataTablesDraw = (selector, order, pages, file, sort, column, template, data_se ...

Using Javascript to fetch undefined data from a C# backend with AJAX

I am struggling to create a web page using Google charts. I attempted to build it with C# as a web form and retrieve data from a local database to JavaScript. However, I keep receiving an error stating that the data is undefined in the response from Ajax. ...

After saving any HTML, SCSS, or TS file, Angular 12 does not compile immediately

Recently I upgraded my Angular project from version 8 to 12 and then migrated to eslint. However, I have encountered an issue where the compilation does not begin immediately after saving a file. There is a delay of approximately 2 minutes before the compi ...

`The function of clicking on a jQuery video is not functioning properly`

Whenever I attempt to click on a video using JavaScript in Firefox to display the video's ID in the console, it seems to not work. Why is this happening? $('.videoclass').click(function() { console.log(this); var id = $(this).attr("id ...

The provider of $modalInstance is currently unknown, leading to an error in the MainController

I'm currently facing an issue with my app's modals when trying to call them using $modalInstance. Despite following the advice from other similar questions I found, such as avoiding the use of ng-controller, my modal still isn't functioning ...