To convert JavaScript object to array, we can use two functions – Object.keys()
and Object.values()
.
Suppose, our javascript object is –
var jsObj = { key1 : 'value 1', key2 : 'value 2', };
Now, if you want to for
loop through this object, you will need to first convert it into array. Because looping through array is possible using count
function. Although in javascript we use length
property.
But first let’s see how we can convert this object to array. Here is the code –
var keyArray = Object.keys(jsObj); var valueArray = Object.values(jsObj);
So, one object could be broken into separate arrays of keys and values. Check out how our keyArray
and valueArray
will look like –
keyArray = ['key1', 'key2'];
valueArray = ['value1', 'value2'];
Using for
loop on javascript object
Now we already know how to convert object to array, so we can simply use that method to iterate on objects. Check out this code –
var keyArray = Object.keys(jsObj); for(var i=0; i < keyArray.length; i++){ console.log("Object Key: ", keyArray[i], ", Object Value: ", jsObj[keyArray[i]]); }
The output of above code will be –
Object Key: key1, Object Value: value1
Object Key: key2, Object Value: value2
A better way to loop through array or object is to use forEach
function. There is no need of count
or length
for iterations through it. Check out the implementation –
Object.keys(jsObj).forEach(function(singleKey){ console.log("Object Key: ", singleKey, ", Object Value: ", jsObj[singleKey]); })
You may also like –
Why we are using array of keys and not array of values while looping?
This is because keys are always unique in an object while values are not. One key will point to its value only but a same value can have many different keys.
So, when we are looping, we can use keys to get the appropriate values. If we have used array of values then we could not get the keys easily.
If you are not required to access keys at all then, yes you can use the array of values in for
or forEach
loop.