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,264
  • 3
  • 36
  • 65
  • Jonathan's answer is what you would like, but to explain your problem, you are attempting to log the value of `arr[k]` plus `dynamicArr` instead of the actual array position. – Thomas Juranek Jan 10 '17 at 05:53
  • Use associative array inside the loop `console.log(arr[k][dynamicArr].name);` – SASIKUMAR S Jan 10 '17 at 05:53

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,439
  • 14
  • 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