0

This is my array

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

To access language.name

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

In arr[k].language.name, i want to put 'language' string as dynamic, which i am getting it from the params of the function arrName. So that it should be

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

Here it is displaying

[object Object].language.name;

How to get actual array value?

Matarishvan
  • 2,382
  • 3
  • 38
  • 68

2 Answers2

5

You need to access the object property the same way you would with an array, only using the string as the key. Like so:

function get(arrName)
{
    for(var k = 0 ; k< arr.length; k++)
    {
        console.log(arr[k][arrName].name);
    }
}
Jonathan Gray
  • 2,509
  • 15
  • 20
2
console.log(arr[k][arrName].name);

It should be, if I recall properly.

Feel free to take a look at this dynamic access to an array in Javascript for an extensive, iterating code.

Kudos on what you made so far, though.

Community
  • 1
  • 1
netpeers
  • 56
  • 4