Get key and value of a JavaScript array into variable

前端 未结 6 1983
时光说笑
时光说笑 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:16

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

提交回复
热议问题