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