Get key and value of a JavaScript array into variable

前端 未结 6 1980
时光说笑
时光说笑 2021-01-12 16:35

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\"         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 17:19

    • 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]]);
      }
    }

提交回复
热议问题