For..In bucles en pares de valores de clave JavaScript


Me preguntaba si hay una manera de hacer algo como un bucle PHP foreach en JavaScript. La funcionalidad que estoy buscando es algo como este fragmento de código PHP:

foreach($data as $key => $value) { }

Estaba mirando el bucle JS for..in, pero parece que no hay manera de especificar el as. Si hago esto con un bucle for ' normal '(for(var i = 0; i < data.length; i++), ¿hay alguna forma de obtener los pares key => value?

Author: TTT, 2011-08-30

14 answers

for (var k in target){
    if (target.hasOwnProperty(k)) {
         alert("Key is " + k + ", value is" + target[k]);
    }
}

hasOwnProperty se utiliza para comprobar si su target realmente tiene esa propiedad, en lugar de haberla heredado de su prototipo. Un poco más simple sería:

for (var k in target){
    if (typeof target[k] !== 'function') {
         alert("Key is " + k + ", value is" + target[k]);
    }
}

Simplemente comprueba que k no es un método (como si target es array obtendrá una gran cantidad de métodos alertados, por ejemplo.indexOf, push, pop, etc.)

 440
Author: J0HN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-30 17:15:16

Nadie ha mencionado Object.keys así que lo mencionaré.

Object.keys(obj).forEach(function (key) {
   // do something with obj[key]
});
 265
Author: goatslacker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-20 17:12:12

El for in funcionará para ti. Si piensa en un objeto como un mapa:

for(key in obj){
    // The key is key
    // The value is obj[key]
}
 85
Author: Paulpro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-30 10:37:22

Si puedes usar ES6 de forma nativa o con Babel (compilador js) entonces podrías hacer lo siguiente:

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

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

Que imprimirá esta salida:

a 1
b 2
c 3

El método Object.entries() devuelve un array de pares [key, value] de la propiedad enumerable de un objeto dado, en el mismo orden que el proporcionado por un bucle for...in (la diferencia es que un bucle for-in también enumera propiedades en la cadena de prototipos).

Espero que ayude! =)

 53
Author: Francesco Casula,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-18 07:58:51
var obj = {...};
for (var key in obj) {
    var value = obj[key];

}

La sintaxis de php es solo sugar.

 52
Author: Zirak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-05 19:00:00

Asumo que sabes que i es la clave y que puedes obtener el valor a través de data[i] (y solo quieres un atajo para esto).

ECMAScript5 introducido forEach [MDN] para arrays (parece que tienes un array):

data.forEach(function(value, index) {

});

La documentación de MDN proporciona un shim para los navegadores que no lo soportan.

Por supuesto, esto no funciona para objetos, pero puede crear una función similar para ellos:

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

Ya que etiquetaste la pregunta con jquery , jQuery proporciona $.each [docs] que recorre ambas estructuras, matriz y objeto.

 16
Author: Felix Kling,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-30 10:44:22
for (var key in myMap) {
    if (myMap.hasOwnProperty(key)) {
        console.log("key =" + key);
        console.log("value =" + myMap[key]);
    }
}

En javascript, cada objeto tiene un montón de pares clave-valor incorporados que tienen meta-información. Cuando haces un bucle a través de todos los pares clave-valor de un objeto, también lo haces a través de ellos. El uso de hasOwnProperty () los filtra.

 7
Author: Siddhu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-19 15:26:04

Puedes usar el for..in para eso.

for (var key in data)
{
    var value = data[key];
}
 6
Author: Christoph Winkler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-30 10:38:04

ES6 proporcionará Mapa.prototipo.forEach (callback) que se puede usar así

myMap.forEach(function(value, key, myMap) {
                        // Do something
                    });
 2
Author: Stephen Murby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-16 13:51:50

Puedes usar un bucle 'for in' para esto:

for (var key in bar) {
     var value = bar[key];
}
 1
Author: Richard Dalton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-30 10:38:24

A continuación se muestra un ejemplo que se acerca lo más posible.

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

Si estás usando jQuery, consulta: http://api.jquery.com/jQuery.each /

 1
Author: Aidamina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-30 10:39:59
let test = {a: 1, b: 2, c: 3};
Object.entries(test).forEach(([key, value]) => console.log(key, value))

// a 1
// b 2
// c 3
 0
Author: 吴毅凡,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-17 11:56:54

Sí, puede tener matrices asociativas también en 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 ...
}
 -2
Author: Alex Pacurar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-30 10:38:44
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;
 -7
Author: user278064,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-30 14:08:33