Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key and value of a JavaScript array into variable

I have a JavaScript object array. When write console.log(myarry) it will show in the console in the below form.

Array[2]
0: Object
one: "one"

1: Object
two: "two"
length: 2

In this array my key and value are same and am trying to get the key or value to a variable and print it. When am trying the below code it showing:

object object

for (var key in myarry) {
 alert("Key is " + key + ", value is" + myarry[key]);
}
like image 524
Jomol MJ Avatar asked Nov 17 '16 05:11

Jomol MJ


3 Answers

check this snippet

var obj = [{
  "1": "one"
}, {
  "2": "two"
}]
obj.forEach(function(item) {
  Object.keys(item).forEach(function(key) {
    console.log("key:" + key + "value:" + item[key]);
  });
});

Hope it helps

like image 110
Geeky Avatar answered Oct 17 '22 00:10

Geeky


  • Use for-loop instead of for-in to iterate array.

  • Use Object.keys to get keys of object

var arr = [{
  one: 'one'
}, {
  two: 'two'
}];

for (var i = 0, l = arr.length; i < l; i++) {
  var keys = Object.keys(arr[i]);
  for (var j = 0, k = keys.length; j < k; j++) {
    console.log("Key:" + keys[j] + "  Value:" + arr[i][keys[j]]);
  }
}
like image 4
Rayon Avatar answered Oct 17 '22 00:10

Rayon


I think you have two main options to get keys of an object using Object.keys these are: forEach; or a simple for.

1. Use forEach

If you're using an environment that supports the Array features of ES5 (directly or using a shim), you can use the new forEach:

var myarray = [{one: 'one'}, {two: 'two'}];

myarray.forEach(function(item) {
  var items = Object.keys(item);
  items.forEach(function(key) {
   console.log('this is a key-> ' + key + ' & this is its value-> ' + item[key]);
 });
});

forEach accepts an iterator function and, optionally, a value to use as this when calling that iterator function (not used above). The iterator function is called for each entry in the array, in order, skipping non-existent entries in sparse arrays. Although

forEach has the benefit that you don't have to declare indexing and value variables in the containing scope, as they're supplied as arguments to the iteration function, and so nicely scoped to just that iteration.

If you're worried about the runtime cost of making a function call for each array entry, don't be; technical details.

2. Use a simple for

Sometimes the old ways are the best:

var myarray = [{one: 'one'}, {two: 'two'}];

for (var i = 0, l = myarray.length; i < l; i++) {
  var items = myarray[i];
  var keys = Object.keys(items);
  for (var j = 0, k = keys.length; j < k; j++) {
    console.log('this is a key-> ' + keys[j] + ' & this is its value-> ' + items[keys[j]]);
  }
}
like image 2
Teocci Avatar answered Oct 17 '22 00:10

Teocci