How to access the value of an array through the key?

1

I have the following array:

var arr = [
  {'David': '1'},
  {'Camilla': '2'},
  {'Sadat': '3'},
  {'Vanuza': '4'}, 
  {'Diego': '5'}
];

I wanted to access the "Camilla" value of the array I created. Ps: I want to access the value of the key and not the index.

    
asked by anonymous 31.03.2016 / 23:04

5 answers

4

You can iterate over the keys of an object using for..in :

var arr = [
  {'David': '1'},
  {'Camilla': '2'},
  {'Sadat': '3'},
  {'Vanuza': '4'}, 
  {'Diego': '5'}
];

arr.forEach(function(objeto) {
  for ( var chave in objeto )
      document.body.innerHTML += "Chave: " + chave + "; Valor: " + objeto[chave] + "<br>";
});

If your object only has a key, this loop will only execute once, so the value you want will be in the chave variable.

However, I would not recommend representing the data this way, unless you have a very good reason for doing so, as well as the way of access being inconvenient still makes it harder to extend the objects in the future (you need to put more properties). Why not use something more structured?

var arr = [
  {nome:'David', valor: '1'},
  {nome:'Camilla', valor: '2'},
  {nome:'Sadat', valor: '3'},
  {nome:'Vanuza', valor: '4'}, 
  {nome:'Diego', valor: '5'}
];
    
31.03.2016 / 23:48
2

If the objects are within an array var ArrayValues ​​= [ { objeto }, { } objeto , ...] ; The following aids of the regular array will work:

  

var ValueDavid = arr [0] .David.toString ();

     

var valueCamilla = arr [1] .Camilla.toString ();

<!DOCTYPE html>
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title></title>
      <meta charset="utf-8" />
      <script>
        function clica() {
          var arr = [
          { 'David': '1' },
          { 'Camilla': '2' },
          { 'Sadat': '3' },
          { 'Vanuza': '4' },
          { 'Diego': '5' }
          ];

          var ValorDavid = arr[0].David.toString();
          var ValorCamilla = arr[1].Camilla.toString();
        }
      </script>



    </head>
    <body>

      <input type=button onClick="clica();" value="Testa">
    </body>
    </html>
    
31.03.2016 / 23:42
2

Following the idea of @Gabriel Katamura, we can create this function:

function getArrValue(arr, m) {
  var filteredArr = arr.find(function(v){ return (m in v); });
  return (!!filteredArr) ? filteredArr[m] : null;
}

Then use getArrValue(arr, 'Camilla') ;)

    
09.06.2016 / 19:34
1
arr.find(function(element) {
  return element.hasOwnProperty('Camilla') 
})['Camilla'];
    
31.03.2016 / 23:08
1

What is the context in which you are using this array?

Maybe the problem is not in how to retrieve the values, but in the data structure you are building.

Your data structure needs to be planned to avoid future problems.

I recommend using a more generic structure, eg:

var arr = [
 { name: 'David', id: '1'},
 { name: 'Camilla', id: '2'},
 { name: 'Sadat', id: '3'},
 { name: 'Vanuza', id: '4'}, 
 { name: 'Diego', id: '5'}
];

This way you will be able to iterate better with your data array when you need it. In this case, for example, you could use a utility library such as lodash (method _.find ) that has several methods that help you manipulate data.

EDITED:

If you still prefer to leave the data structure the way it is or can not change it, you can create a function to access the value:

function getValueByKey (collection, key) {
  var value;

  collection.map(function (item) {
    if (key in item) value = item[key];
  })

  return value;
}

link

    
01.04.2016 / 03:46