开发者

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(v开发者_JAVA技巧ar i = 0; i < data.length; i++), is there a way to grab the key => value pairs?


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 can use ES6 natively or with Babel (js compiler) then you could do the following:

const test = {a: 1, b: 2, c: 3};

for (const [key, value] of Object.entries(test)) {
  console.log(key, value);
}

Which will print out this output:

a 1
b 2
c 3

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

  • Object.entries documentation
  • for...of documentation
  • Destructuring assignment documentation
  • Enumerability and ownership of properties documentation


No one has mentioned Object.keys so I'll mention it.

Object.keys(obj).forEach(function (key) {
   // do something with obj[key]
});


for...in will work for you.

for( var key in obj ) {
  var value = obj[key];
}

In modern JavaScript you can also do this:

for ( const [key,value] of Object.entries( obj ) ) {

}


var obj = {...};
for (var key in obj) {
    var value = obj[key];

}

The php syntax is just sugar.


I assume you know that i is the key and that you can get the value via data[i] (and just want a shortcut for this).

ECMAScript5 introduced forEach [MDN] for arrays (it seems you have an array):

data.forEach(function(value, index) {

});

The MDN documentation provides a shim for browsers not supporting it.

Of course this does not work for objects, but you can create a similar function for them:

function forEach(object, callback) {
    for(var prop in object) {
        if(object.hasOwnProperty(prop)) {
            callback(prop, object[prop]);
        }
    }
}

Since you tagged the question with jquery, jQuery provides $.each [docs] which loops over both, array and object structures.


for (var key in myMap) {
    if (myMap.hasOwnProperty(key)) {
        console.log("key =" + key);
        console.log("value =" + myMap[key]);
    }
}

In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. The use of hasOwnProperty() filters these out.


There are three options to deal with keys and values of an object:

  1. Select values:

    Object.values(obj).forEach(value => ...);
    
  2. Select keys:

    Object.keys(obj).forEach(key => ...);
    
  3. Select keys and values:

    Object.entries(obj).forEach(([key, value]) => ...);
    


You can use the for..in for that.

for (var key in data)
{
    var value = data[key];
}


let test = {a: 1, b: 2, c: 3};
Object.entries(test).forEach(([key, value]) => console.log(key, value))

// a 1
// b 2
// c 3


In the last few year since this question was made, Javascript has added a few new features. One of them is the Object.Entries method.

Copied directly from MDN is the follow code snippet


const object1 = {
  a: 'somestring',
  b: 42
};

for (let [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}


ES6 will provide Map.prototype.forEach(callback) which can be used like this

myMap.forEach(function(value, key, myMap) {
                        // Do something
                    });


You can use a 'for in' loop for this:

for (var key in bar) {
     var value = bar[key];
}


Below is an example that gets as close as you get.

for(var key in data){
  var value = data[key];    
  //your processing here
}

If you're using jQuery see: http://api.jquery.com/jQuery.each/


If you are using Lodash, you can use _.forEach

_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key + ": " + value);
});
// => Logs 'a: 1' then 'b: 2' (iteration order is not guaranteed).


why not simply this

var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }];

donuts.forEach(v => {console.log(v["type"]+ " donuts cost $"+v["cost"]+" each")});


Please try the below code:

<script> 
 const games = {
  "Fifa": "232",
  "Minecraft": "476",
  "Call of Duty": "182"
 };

Object.keys(games).forEach((item, index, array) => {
  var msg = item+' '+games[item];
  console.log(msg);
});


yes, you can have associative arrays also in javascript:

var obj = 
{
    name:'some name',
    otherProperty:'prop value',
    date: new Date()
};
for(i in obj)
{
    var propVal = obj[i]; // i is the key, and obj[i] is the value ...
}


var global = (function() {
   return this;
})();

// Pair object, similar to Python

function Pair(key, value) {
    this.key = key;
    this.value = value;

    this.toString = function() {
       return "(" + key + ", " + value + ")";
    };
}

/**
 * as function
 * @param {String} dataName A String holding the name of your pairs list.
 * @return {Array:Pair} The data list filled
 *    with all pair objects.
 */
Object.prototype.as = function(dataName) {
    var value, key, data;
    global[dataName] = data = [];

    for (key in this) {
       if (this.hasOwnProperty(key)) {
          value = this[key];

          (function() {
             var k = key,
                 v = value;

            data.push(new Pair(k, v));
          })();
       }
    }

    return data;
};

var d = {
   'one': 1,
   'two': 2
};

// Loop on your (key, list) pairs in this way
for (var i = 0, max = d.as("data").length; i < max; i += 1) {
   key = data[i].key;
   value = data[i].value;

   console.log("key: " + key + ", value: " + value);
}

// delete data when u've finished with it.
delete data;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜