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

Asked

Viewed 4,348 times

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 key value and not the index.

  • Do you want, for each element of the array, to access the key? Or is it for a specific element? These elements only have a key/value pair?

5 answers

5


You can iterate over the keys of an object using the 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 one key, this loop will only run once, then the value you want will be in the variable chave.

However, I would not recommend representing the data in this way unless you have a very good reason for doing so, as in addition to the inconvenient way of accessing it still makes it more difficult to extend the objects in the future (will 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'}
];

2

Following the idea of @Gabriel Katamura, we have how to create this function:

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

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

2

If objects are inside an array var ArrayValues ​​= [ { objeto }, { } objeto , ...] ; The following regular parent advisors will work:

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

var Valorcamilla = 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>

1

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

Maybe the problem is not how to recover the values, but in the data structure that is building.

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

I recommend using a more generic structure, example:

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 matrix when you need it. In this case for example you could use a utility library like lodash (method _.find) that has various methods that helps you manipulate data.


EDITED:

If you still prefer to leave the data structure the way it is or can’t 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;
}

https://jsfiddle.net/t0kt8vkn/

1

arr.find(function(element) {
  return element.hasOwnProperty('Camilla') 
})['Camilla'];
  • Sorry, I edited the title of the question so you understand better Gabriel

Browser other questions tagged

You are not signed in. Login or sign up in order to post.