I was wondering if there's a way to do something like a PHP foreach
loop in JavaScript. The functionality I'm looking for is something like this PHP Snippet:
foreach($data as $key => $value) { }
I was looking at the JS for..in
loop, but there seems to be no way to specify the as
. If I do this with a 'normal' for loop (for(var i = 0; i < data.length; i++
), is there a way to grab the key => value pairs?
Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.
The for...in loop is used to loop through objects. for (key in object) { // Things to do in the loop } The first part, the key , is the name of the variable to assign to the current object key in the loop.
You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.
A property is a “key: value” pair, where key is a string (also called a “property name”), and value can be anything. We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It's easy to find a file by its name or add/remove a file.
for (var k in target){ if (target.hasOwnProperty(k)) { alert("Key is " + k + ", value is " + target[k]); } }
hasOwnProperty
is used to check if your target
really has that property, rather than having inherited it from its prototype. A bit simpler would be:
for (var k in target){ if (typeof target[k] !== 'function') { alert("Key is " + k + ", value is" + target[k]); } }
It just checks that k
is not a method (as if target
is array
you'll get a lot of methods alerted, e.g. indexOf
, push
, pop
,etc.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With