Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For..In loops in JavaScript - key value pairs

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?

like image 616
Joris Ooms Avatar asked Aug 30 '11 10:08

Joris Ooms


People also ask

Can we loop an object which is like 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.

What is key in for in loop in JavaScript?

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.

How do you iterate through an array of key-value pairs in JavaScript?

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.

What is key value pair in JavaScript?

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.


1 Answers

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.)

like image 63
J0HN Avatar answered Oct 20 '22 03:10

J0HN