Get key and value of java script array in variable

I have an array of java-script objects. When writing console.log (myarry), it will be displayed in the console in the form below.

Array[2] 0: Object one: "one" 1: Object two: "two" length: 2 

In this array, my key and value are the same, and I'm trying to get the key or value of a variable and print it. When I try to use the code below, it shows the object of the object.

 for (var key in myarry) { alert("Key is " + key + ", value is" + myarry[key]); } 

Please help me solve this.

+1
source share
5 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 this helps

+2
source
  • Use for-loop instead of for-in to iterate through the array.

  • Use Object.keys to get the keys to 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]]); } } 
+1
source

I think you have two main options: forEach or simple for in combination with Object.keys to get the keys of an object

1. Use forEach

If you are using an environment that supports Array ES5 features (directly or via a strip), 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 used as this when calling this iterator function (not used above). An iterator function is called for each record in the array to skip non-existent records in sparse arrays. Although

forEach has the advantage that you do not need to declare indexing and variable values ​​in the content area, since they are supplied as arguments to the iteration function and are therefore perfectly tied to this iteration.

If you are worried about the cost of executing a function call for each array entry, you should not; 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]]); } } 
+1
source

I'm trying to get the key or value of a variable and print it.

then you could

 for (var key in myarry) { var value = myarry[key]; } 
0
source

you can do it this way

 a.forEach(function(value,key) { console.log(value,key); }); 

You can take the key and value in a variable and use them.

0
source

Source: https://habr.com/ru/post/1012408/


All Articles