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

The rendering of the input dropdown control in Angular JS is experiencing difficulties

I am currently using your Angular JS Input Dropdown control, and I have followed the code example provided on your demo page in order to implement the control on a specific page of my website built with PHP Laravel. However, I have encountered an issue dur ...

Determine changes in data retrieved from a JSON file using React

I've been working on a cryptocurrency app using React and a JSON API to fetch the latest data. My approach involves using fetch to load the JSON API and setInterval to refresh the app every 10 seconds. Now, I'm wondering if there's a way to ...

Tips for storing arrays in AngularJS with JavaScript

I am new to using JavaScript. I have a function that stores objects in an array to an Angular model. Here is an example: function getSpec(){ debugger var i; for(i=0;i<main.specifications.length;i++){ main.newProduct.Specification= ( ...

Transferring values between arrays in PHP: A step-by-step guide

For instance: $item = Array( [0] => Array( [id]="1" [file]="new" ) [1] => Array( [id]="2" [file]="sample" ) [2] => Array( [id]="3" [file]="hello" ) [3] => Array( [id]="4" [file]="garden" ) [4] => Array( [id]="5" [file]="door" ) [5] => Ar ...

The JSON response from PayPal's OAuth login access did not return any data

I am facing an issue with two PHP files, namely index.php and paypal.php. The code snippet for paypal.php is as follows: <?php session_start(); $client_id = 'xxxxxxxxxxxx'; $client_secret = 'xxxxxxxxxxxxxxxxxxxx' ...

Is there a way to establish a default URL for the first image in Carrierwave?

I've set up a standard image uploader using Carrierwave in conjunction with Postgres. Here's what my migration looks like for adding images as JSON: class AddImagesToListings < ActiveRecord::Migration[5.1] def change add_column :listing ...

Utilizing material-ui textfield involves a delay when the input is being focused

Is there a way to trigger inputRef.current.focus() without relying on setTimeout? It seems like the focus is not working as expected in React or MaterialUI. For a demonstration, visit: https://codesandbox.io/s/goofy-gareth-lkmq3?file=/src/App.js export de ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

Utilize Avro Schema to reference enumerations stored in a JSON file

While crafting an Avro schema for a Kafka topic, I am incorporating an Enum field. This schema will ultimately be uploaded to the Kafka schema registry. In my GitHub repository, I have a JSON file named validValues.json, structured as shown below: { &qu ...

The Helper Text fails to display the error, and the error message does not appear when the login data is incorrect

Currently, I am facing an issue with displaying error messages within my helper text component while using Material UI. Despite successfully testing my backend code using Postman to identify errors, I am unable to see the error message under the button whe ...

Building a dynamic URL in ReactJS from scratch

const selectedFilters = { category: "", mealtype: "lunch", cuisinetype: "Italian", dishType: "Pasta" } const apiUrl = `https://api.edamam.com/api/recipes/v2?type=public&q=${query}&app_id=${app_id}&app_key=${app_key}`; User ...

Is AngularJS the right choice for developing this application?

Recently, I've come to the realization that I want to dive into the world of AngularJS framework after working with jQuery for several years. I have a vision of developing an application that allows users to easily modify webpage DOM using a browser- ...

Is it possible to enable auto play on HTML5 Video for iPad similar to BBC iPlayer?

Can HTML5 Videos automatically play on iPads? I used to believe that it wasn't possible because of iOS restrictions, but after trying BBC iPlayer on my iPad, I noticed that the videos did autoplay upon loading. Could this indicate that it is indeed ...

Incorporate dots into every slide using the React Slick slider

When implementing a slider in React.js, I use React Slick. The API provided by React Slick allows us to easily incorporate previous and next buttons on each slide using the Previous and Next methods. However, I am curious about how to achieve the same fun ...

Problems arise with identification of asynchronous functions

My async functions have been used successfully in various projects, but when incorporating them into a new project, they suddenly stopped working. One of the functions causing trouble is: const ddbGet = async (params) => { try { const data ...

Issue with Angular ngModel not syncing with variable changes

Currently using Angular 4 and Typescript, I have a table containing <select> elements in my template: <tr *ngFor="let task of tasksDetails"> <td>{{task.name}}</td> <td> <select class="form-control" [(ngMode ...

Dealing with TSLint errors within the node_modules directory in Angular 2

After installing the angular2-material-datepicker via NPM, it is now in my project's node_modules folder. However, I am encountering tslint errors that should not be happening. ERROR in ./~/angular2-material-datepicker/index.ts [1, 15]: ' should ...

Using jQuery and Flask-WTF to achieve live word count in a TextAreaField - a step-by-step guide!

I am interested in adding a real-time word count feature to a TextAreaField using jQuery. I found an example that I plan to use as the basis for my code: <html lang="en"> <head> <script src= "https://code.jquery.com/jquery ...

Explore the XML format within a JavaScript string

Currently, I am retrieving a string from PHP using AJAX. This string contains data from a database formatted in XML tags. Upon receiving this string in JavaScript, my objective is to display it as an XML document on the web browser to verify its proper fo ...

Concealing tab bars on Ionic 2 secondary pages

In my Ionic Bootstrap configuration, I have the following setup: { mode: 'md', tabsHideOnSubPages: true } However, despite having this setting in place, the tabs still appear on some sub-pages. It seems to be happening randomly. Is there ...