Modify the value of the 'key' within an array in JavaScript

Here is the array I am working with:

[
  {    
    "id": 2,
    "language": {
      "name": "English",
      "abbreviation": "EN"
  }
]  

To access the value of language.name:

function get(arrName)
{
    for(var k = 0; k < arr.length; k++)
    {
        console.log(arr[k].language.name); // English
    }
}

In the expression arr[k].language.name, I want to make 'language' dynamic by getting it from the parameter of the function, arrName. So it should look like this:

function get(arrName)
{
    for(var k = 0 ; k< arr.length; k++)
    {
        var dynamicArr = '.' + arrName + '.name';
        console.log(arr[k] + dynamicArr);
    }
}

However, the output currently shows:

[object Object].language.name;

How can I retrieve the actual value from the array?

Answer №1

To retrieve the value of an object property within an array, you can access it by using the string as the key in a similar way to accessing elements in an array. Here is an example:

function getProperty(objectArray, propertyName)
{
    for(var i = 0; i < objectArray.length; i++)
    {
        console.log(objectArray[i][propertyName]);
    }
}

Answer №2

console.log(arr[k][arrName].name);

It seems like it should be correct.

Check out this helpful resource on accessing arrays dynamically in Javascript for more information and code examples.

You're doing a great job with your progress so far!

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

How to make the slides in a Bootstrap 4 carousel slide in and out with animation

I'm currently utilizing the bootstrap 4 carousel and have made some customizations to fit my project needs. The main requirement is: When I click on the next slide, the current next slide should become active and a new next slide should load with ...

Leveraging the power of AWS API Gateway and Lambda for seamless image upload and download operations with Amazon

I have successfully created a lambda function to handle image uploads and downloads to s3. However, I am encountering difficulties with the proxy integration from the API Gateway. Despite reviewing the documentation and looking at this specific question ...

Update overall font size to be 62% for a consistent look across the website

Recently, I developed a browser extension that adds an overlay button to the LinkedIn website. Everything was running smoothly until I discovered that LinkedIn uses a global font-size: 62,5% that completely messes up my design.. https://i.stack.imgur.com ...

HTML element DIV positioned above the iframe

I am looking for a way to automatically place a "PLAY" div above each iframe instead of doing it manually. I have successfully done it manually but I'm not sure how to achieve the same result with a script or using CSS. Below is my HTML markup: < ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...

Show an error message in a popup window, following a validation error in Laravel

I am facing an issue with displaying error messages in the update modal form. I am using Laravel request for validation and AJAX to submit the form inside a modal. My goal is to show the error message for each field that is inputted incorrectly. However, i ...

Guide on generating virtual nodes from a string containing HTML tags using Vue 3

Investigation I stumbled upon this solution for converting a simple SVG with one path layer into Vue2 vnode list and wanted to adapt it for Vue3. After scouring resources, including the MDN docs, I couldn't find any pre-existing solutions. So, I dec ...

When the ASPxComboBox component is situated within two ASPxPageControl tab pages, I am unable to access it

I am encountering an issue with accessing the ASPxComboBox component when it is within an ASPxPageControl that has multiple tab pages. To handle this, I have added a function to the ClientSideEvents using string.Format: function(s, e) {{ if (window[ ...

An issue has occurred: function() is not a valid function

Issue: core.mjs:10132 ERROR TypeError: block.getDepartment is not a function at FirebaseService.mapDatabaseToBlock (firebase.service.ts:54:30) at firebase.service.ts:45:60 at Array.map (<anonymous>) at firebase.service.ts:45:42 at ...

I am looking to create a side menu that will allow for dynamic class changes upon clicking

I'm looking to create a dynamic side menu that changes class on click event. My goal is to have jQuery add a class to a clicked "li" element that doesn't already have the class "active", while removing the class from other "li" elements. I want ...

My Node.js script seems to be experiencing some issues

Could you provide me with a helpful tip? Here is the code I am working on: const request = require('request'); const cheerio = require('cheerio'); function getUrls(url) { const baseUrl = 'https://unsplash.com'; let u ...

What is the method for showcasing an image before it has been uploaded?

I must start by apologizing for my English, as I am not the most fluent speaker. Here's where I'm facing a dilemma: I have created an application that allows users to edit questions for a game. These questions are stored on a server and can be ...

Navigational menu header leads to specific location on the page

I need the dropdown menu header to both open the related menu and display the content of the first element of the submenu, which is an anchor link on the page. Here is the HTML code for the Dropdown Menu: <div class="collapse navbar-collapse" id="myNa ...

Get a reference to pass as an injection into a child component using Vue js

Is there a way to pass a reference to child components? For example: The Parent component provides the ref: <template> <div ref="myRef" /> </template> <script> export default { name: 'SearchContainer', pr ...

Gulp encountered an issue - Module 'sigmund' not found

After installing browser-sync, my previously working Gulp encountered an error: Error: Cannot find module 'lru-cache' To resolve this issue, I utilized the following solution: npm link lru-cache as suggested in this thread However, upon atte ...

Looking to incorporate AAD calling functionality in a React and Node application by utilizing the Graph API for communication/calls

As a newcomer to Microsoft Azure and its services, I recently registered an application with Azure. However, when attempting to integrate a call feature in my Web App using the graph API '/communication/calls', I encountered the following error m ...

"Discovering a button press using the Gamepad API: A Step-by-Step Guide

I'm currently building a web page that can detect button presses on an Xbox controller and display a boolean value based on the pressed button. Right now, I have successfully managed to detect when a controller is connected and show it as a string. Ho ...

Instructions for launching an Android app from a website

Is it possible to invoke my app from HTML? For instance, I am able to successfully call a webpage from my app using this code. android code: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse( "myDomain.com"))); ...

It is not possible to recycle a TinyMCE editor that is embedded in a popup

Having a frustrating issue with the TinyMCE Editor plugin embedded within a Fancybox pop-up window. I have a list of objects with Edit links that trigger an AJAX call to retrieve content from the server and place it in a <textarea>. A TinyMCE editor ...

A guide on determining the width and height of individual characters within a span of text

What is the most effective method for determining the width and height of each character within a span element? For example, if the HTML code looks like this: <span style="font-size:12px">Test 100</span> One approach is to create a dummy spa ...