Switch up the key while iterating through a JSON object

Can you modify the key while iterating through objects using an external variable? Picture it like this:

var data = [{
    "id": 1,
    "name": "Simon",
    "age": 13
}, {
    "id": 2,
    "name": "Helga",
    "age": 18
}, {
    "id": 3,
    "name": "Tom",
    "age": 27
}, ]

var key = name;

for (var i = 0; i < data.length; i++) {
    var output = data[i].key;
}

However, this currently results in an undefined output. The aim is to create a function that can manage various types of loops.

Answer №1

To access objects in JavaScript, you can use a similar syntax to arrays. Here is an example of the code you need:

var data = [{
    "id": 1,
    "name": "Simon",
    "age": 13
}, {
    "id": 2,
    "name": "Helga",
    "age": 18
}, {
    "id": 3,
    "name": "Tom",
    "age": 27
}]

var key = "name";

for (var i = 0; i < data.length; i++) {
    var output = data[i][key];
}

In regard to the now-deleted previous answer, I suggest avoiding using foreach since it is not compatible with Internet Explorer 8.

Instead, consider using:

var key = "name";

for (var i in data) {
  if(data.hasOwnProperty(i))
  {
    var output = data[i][key];
  }
}

Answer №2

A possible solution to your problem could be a function similar to the one below:

function extractValueFromArray(array, value) {
    for (var idx in array) {
        //perform actions using array[idx][value]
    }
}

To use this function, simply call it with the desired parameters like so:

extractValueFromArray(data, "title")

This function is designed to handle the extraction of specific values from an array of objects. It can be customized further according to specific requirements, but I've kept it concise for simplicity.

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

Chrome on OSX Mavericks threw a RangeError because the maximum call stack size was exceeded

While attempting to run an Angular app using linemanjs in Chrome on a Mac, I encountered the following error: Uncaught RangeError: Maximum call stack size exceeded An interesting observation is that the site functions properly on Chrome on a Windows mach ...

Modify a property within an object and then emit the entire object as an Observable

I currently have an object structured in the following way: const obj: SomeType = { images: {imageOrder1: imageLink, imageOrder2: imageLink}, imageOrder: [imageOrder1, imageOrder2] } The task at hand is to update each image within the obj.images array ...

Unveiling the Secrets of AJAX Requests with Enigmatic Strings Attached to URLs

My goal is to keep track of cricket scores on scorespro/cricket by utilizing browser AJAX requests. By analyzing the network traffic in Google Chrome, I have noticed that my browser sends out requests in this format: Whenever I click on the response withi ...

Strengthening JavaScript Security

Throughout the past few years, I have delved into various javascript libraries like Raphael.js and D3, experimenting with animations sourced from different corners of the internet for my own learning. I've obtained code snippets from Git repositories ...

Failure to receive a server response during the AJAX communication

I am facing an issue with my code that is making 3 requests to a server. The code successfully sends the request, but fails when receiving the response. I need help in skipping the first response and only getting the third one. phone.open("POST", '/& ...

Finding the position of the latest item added to an array

If I add an element into an array in this way: $arr[] = 'something'; How can I determine the index of 'something'? Is there a different approach to adding an element to the array and finding its index? ...

Showing the ng-controller contents post executing AJAX request using the "as" method

My goal is to display the contents of ng-repeat after making an AJAX call using $http. <table ng-controller="TableController as tc"> <tr> <th>Date</th> <!-- other headers are here --> ...

Executing script once the DOM has completed loading

In my project, I'm dynamically generating menu items for a menu bar based on headers from external files that are imported using an XMLHttpRequest(). The menu bar is then updated as I navigate through different pages. Everything works smoothly. Each ...

Converting numbers to strings based on locale in React Native

I have a quantity that, when using the amount.toFixed() function, produces the string "100.00". I would like this result to be formatted according to the specific locale. For example, in Italian the desired output is 100,00, while in English it should be ...

Tips for verifying the rendered view post data retrieval from an API in Vue JS

Having trouble retrieving data from the API using Vue JS and printing the page? After fetching the data, some elements may not render completely when trying to print, resulting in blank data being displayed. While using a setTimeout function may work for s ...

JavaScript encoding and decoding challenges

Can anyone help me figure out what's wrong? I'm trying to encode and decode a simple input, but it just doesn't seem to work! Any ideas why? Thanks in advance for your assistance :) ENCODE: function encryption_encode(s, delta) { var te ...

Uploading files and data in Laravel using Vue.js and Vuetify: A step-by-step guide

My Vuetify form is working fine with text input, but when I try to include images, I encounter the error GET http://danza.test/thumbnails[object%20File] 404 (Not Found). How can I successfully pass both text and images in a form? This is part of the code ...

The Bootstrap nav-tab functions perfectly on a local server, but unfortunately does not work when hosted remotely

UPDATE: Issue resolved so I have removed the Github link. It turns out that Github pages require a secure https connection for all linked scripts. Always remember to check the console! I encountered an unusual bug where the Bootstrap nav-tab functionality ...

Embracing the Quirks of JSON: A Call for a

Currently, I am in the process of developing a webpage that involves incorporating four distinct JSON entities (objects, arrays). Excuse my lack of appropriate jargon. Upon receiving the JSON data, it is structured as an object with numerous sub-objects, ...

Is there a specific method or function that can effectively translate special characters such as into their corresponding representations?

When a user provides input for my script using shell arguments, it would look something like this: Kek kek\nkek\tkek\x43 After receiving the input, Javascript interprets my parameter in a specific way: var parameter="Kek kek\&bs ...

Strange rendering issues when using the react material-ui dialog

Exploring the Project Recently, I developed a front-end project focusing on a delivery service using React and Material UI. One interesting feature I added was a Dialog window that pops up when users click on an item, allowing them to customize it. Here i ...

Hover over with your mouse to open and close the dropdown menu in React JS

Just starting out with React JS and encountering a small issue. I'm trying to make the menu disappear when the mouse leaves that area, so I used onMouseOut and onMouseLeave to close it. However, I noticed that having these options in place prevents th ...

Can someone advise me on how to ensure my function effectively delivers a desired outcome?

My goal is to learn Javascript on my own, but I'm struggling to make progress. I've created a function called fixedSpending() that takes two inputs, num1 and num2, and adds them together. However, when the user hits the "=" button, I expect the f ...

Creating a JSON file in Android using Python when it is not already present

I'm currently developing an application that allows users to input information and save the data into a json file named hello.json. Everything works smoothly when the file already exists, but during testing on an Android device, the app crashes becaus ...

Incorporate attributes into object properties in a dynamic manner

Currently, I am experimenting with bootstrap-multiselect and my goal is to incorporate data attributes into the dataprovider method. Existing Data Structure: var options = [ {label: 'Option 1', title: 'Option 1', value: ' ...