¿Cómo puedo recorrer o enumerar un objeto JavaScript?


Tengo un objeto JavaScript como el siguiente:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

Ahora quiero recorrer todos los elementos p (p1, p2, p3...) Y obtener sus claves y valores. ¿Cómo puedo hacer eso?

Puedo modificar el objeto JavaScript si es necesario. Mi objetivo final es recorrer algunos pares de valores clave y, si es posible, quiero evitar usar eval.

Author: Luca Kiebel, 2009-03-26

30 answers

Puede usar el bucle for-in como lo muestran otros. Sin embargo, también debe asegurarse de que la clave que obtiene es una propiedad real de un objeto y no proviene del prototipo.

Aquí está el fragmento:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}
 3589
Author: levik,
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-10-18 09:42:09

Bajo ECMAScript 5, puede combinar Object.keys() y Array.prototype.forEach():

var obj = { first: "John", last: "Doe" };

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});

ES6 añade for...of:

for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

ES2017 añade Object.entries() lo que evita tener que buscar cada valor en el objeto original:

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

Tanto Object.keys() como Object.entries() iteran las propiedades en el mismo orden que un bucle for...in pero ignoran la cadena de prototipos. Solo se iteran las propiedades enumerables propias del objeto.

Editar: ES2016 → ES6

 675
Author: Axel Rauschmayer,
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-05-08 18:51:21

Tienes que usar el bucle for-in

Pero tenga mucho cuidado al usar este tipo de bucle, porque esto bucle todas las propiedades a lo largo de la cadena de prototipos.

Por lo tanto, al usar bucles for-in, siempre use el método hasOwnProperty para determinar si la propiedad actual en iteración es realmente una propiedad del objeto que está verificando:

for (var prop in p) {
    if (!p.hasOwnProperty(prop)) {
        //The current property is not a direct property of p
        continue;
    }
    //Do your logic with the property here
}
 306
Author: Andreas Grech,
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-02-24 10:51:33

La pregunta no estará completa si no mencionamos métodos alternativos para bucear a través de objetos.

Hoy en día muchas bibliotecas JavaScript bien conocidas proporcionan sus propios métodos para iterar sobre colecciones, es decir, sobre matrices , objetos , y objetos similares a una matriz. Estos métodos son convenientes de usar y son totalmente compatibles con cualquier navegador.

  1. Si trabaja con jQuery , puede utilizar jQuery.each() método. Se puede usar para iterar sin problemas sobre objetos y matrices:

    $.each(obj, function(key, value) {
        console.log(key, value);
    });
    
  2. {[16] {} En[29]}Subrayado.js puedes encontrar el método _.each(), que itera sobre una lista de elementos, rindiendo cada uno a su vez a una función suministrada (preste atención al orden de los argumentos en iteratee función!):
    _.each(obj, function(value, key) {
        console.log(key, value);
    });
    
  3. Lo-Dash proporciona varios métodos para iterar sobre propiedades de objetos. Básico _.forEach() (o es alias _.each()) es útil para bucear a través de objetos y matrices, sin embargo (!) los objetos con la propiedad length se tratan como matrices, y para evitar este comportamiento se sugiere utilizar _.forIn() y _.forOwn() métodos (estos también tienen value argumento que viene primero):

    _.forIn(obj, function(value, key) {
        console.log(key, value);
    });
    

    _.forIn() itera sobre propiedades propias y heredadas enumerables de un objeto, mientras que _.forOwn() itera solo sobre propiedades propias de un objeto (básicamente comprobando con la función hasOwnProperty). Para objetos simples y literales de objetos cualquiera de estos métodos funcionará bien.

Generalmente todos los métodos descritos tienen el mismo comportamiento con cualquier objeto suministrado. Además de usar el bucle nativo for..in normalmente será más rápido que cualquier abstracción, como jQuery.each(), estos métodos son considerablemente más fáciles de usar, requieren menos codificación y proporcionan un mejor manejo de errores.

 233
Author: VisioN,
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-06-08 19:43:59

En ECMAScript 5 tiene un nuevo enfoque en los campos de iteración de literal - Object.keys

Más información se puede ver en MDN

Mi elección está a continuación como una solución más rápida en las versiones actuales de los navegadores (Chrome30, IE10, FF25)

var keys = Object.keys(p),
    len = keys.length,
    i = 0,
    prop,
    value;
while (i < len) {
    prop = keys[i];
    value = p[prop];
    i += 1;
}

Puede comparar el rendimiento de este enfoque con diferentes implementaciones en jsperf.com :

Soporte del navegador se puede ver en Tabla compat de Kangax

Para el navegador antiguo tienes simple y completo polyfill

UPD:

Comparación de rendimiento para todos los casos más populares en esta pregunta en perfjs.info:

Iteración literal del objeto

 48
Author: Pencroff,
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-09-12 22:11:09

Puedes iterar sobre él como:

for (var key in p) {
  alert(p[key]);
}

Tenga en cuenta que key no tomará el valor de la propiedad, es solo un valor de índice.

 34
Author: Bryan,
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-10-09 15:11:27

Desde que es2015 es cada vez más popular, estoy publicando esta respuesta que incluye el uso del generador y el iterador para iterar sin problemas a través de pares [key, value]. Como es posible en otros lenguajes por ejemplo Ruby.

Ok aquí hay un código:

const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
  [Symbol.iterator]: function* () {
    for (const i of Object.keys(this)) {
      yield [i, this[i]];
    }
  }
};

for (const [k, v] of MyObject) {
  console.log(`Here is key ${k} and here is value ${v}`);
}

Toda la información sobre cómo se puede hacer un iterador y generador se puede encontrar en la página del desarrollador Mozilla.

Espero que haya ayudado a alguien.

EDITAR:

ES2017 incluirá Object.entries que hará iteración sobre [key, value] pares en objetos aún más fácil. Ahora se sabe que será parte de un estándar de acuerdo con la información de la etapa ts39.

Creo que es hora de actualizar mi respuesta para que se vuelva aún más fresca de lo que es ahora.

const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
};

for (const [k, v] of Object.entries(MyObject)) {
  console.log(`Here is key ${k} and here is value ${v}`);
}

Puede encontrar más información sobre el uso en MDN page

 24
Author: FieryCod,
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-30 14:34:36

Prefacio:

  • Las propiedades del objeto pueden ser propias (la propiedad está en el objeto en sí) o heredadas (no en el objeto en sí, en uno de sus prototipos).
  • Las propiedades de los objetos pueden ser enumerableso no enumerables. Las propiedades no enumerables se dejan fuera de muchas enumeraciones/matrices de propiedades.
  • Los nombres de propiedad pueden ser cadenas o Símbolos. Las propiedades cuyos nombres son Símbolos se dejan fuera de muchas propiedades enumeraciones / arrays.

Aquí en 2018, sus opciones para recorrer las propiedades de un objeto son:

  1. for-in [MDN, spec ] - Una estructura de bucle que recorre los nombres de las propiedades enumerables de un objeto, incluidas las heredadas, cuyos nombres son cadenas
  2. Object.keys [MDN, spec ] - Una función que proporciona una matriz de los nombres de propios, propiedades enumerables cuyos nombres son cadenas.
  3. Object.values [MDN, especificación] - Una función que proporciona una matriz de los valores de un objeto propio, enumerable propiedades.
  4. Object.entries [MDN, spec ] - Una función que proporciona una matriz de los nombres y valores propios de un objeto , propiedades enumerables.
  5. Object.getOwnPropertyNames [MDN, spec ] - Una función que proporciona una matriz de los nombres de las propiedades propias de un objeto (incluso las no enumerables) cuyos nombres son cadenas.
  6. Object.getOwnPropertySymbols [MDN, spec ] - Una función que proporciona una matriz de los nombres de las propiedades propias de un objeto (incluso las no enumerables) cuyos nombres son Símbolos.
  7. Reflect.ownKeys [MDN, especificación] - Una función que proporciona una matriz de la nombres de las propiedades propias de un objeto (incluso las no enumerables), ya sean cadenas o Símbolos.
  8. Si desea todas las propiedades de un objeto, incluidas las heredadas no enumerables, debe usar un bucle y Object.getPrototypeOf [MDN, spec ] y uso Object.getOwnPropertyNames, Object.getOwnPropertySymbols, o Reflect.ownKeys en cada objeto de la cadena de prototipos (ejemplo en la parte inferior de esta respuesta).

Con todos ellos excepto for-in, usarías algún tipo de bucle construir en la matriz (for, for-of, forEach, etc.).

Ejemplos:

for-in:

// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name in o) {
    const value = o[name];
    console.log(`${name} = ${value}`);
}

Object.keys (con un bucle for-of, pero puede usar cualquier bucle construir):

// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.keys(o)) {
    const value = o[name];
    console.log(`${name} = ${value}`);
}

Object.values:

// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const value of Object.values(o)) {
    console.log(`${value}`);
}

Object.entries:

// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const [name, value] of Object.entries(o)) {
    console.log(`${name} = ${value}`);
}

Object.getOwnPropertyNames:

// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertyNames(o)) {
    const value = o[name];
    console.log(`${name} = ${value}`);
}

Object.getOwnPropertySymbols:

// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertySymbols(o)) {
    const value = o[name];
    console.log(`${String(name)} = ${value}`);
}

Reflect.ownKeys:

// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Reflect.ownKeys(o)) {
    const value = o[name];
    console.log(`${String(name)} = ${value}`);
}

Todas las propiedades , incluidas las heredadas no enumerables:

// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {
    for (const name of Reflect.ownKeys(current)) {
        const value = o[name];
        console.log(`[${depth}] ${String(name)} = ${String(value)}`);
    }
}
.as-console-wrapper {
  max-height: 100% !important;
}
 18
Author: T.J. Crowder,
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-07-10 10:39:33

Via prototype with forEach () which should skip the prototype chain properties:

Object.prototype.each = function(f) {
    var obj = this
    Object.keys(obj).forEach( function(key) { 
        f( key , obj[key] ) 
    });
}


//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3
 17
Author: bitstrider,
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
2012-12-09 05:05:51

Después de revisar todas las respuestas aquí, hasOwnProperty no es necesario para mi propio uso porque mi objeto json está limpio; realmente no tiene sentido agregar ningún procesamiento javascript adicional. Esto es todo lo que estoy usando:

for (var key in p) {
    console.log(key + ' => ' + p[key]);
    // key is key
    // value is p[key]
}
 15
Author: Francis Lewis,
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-18 20:50:22
for(key in p) {
  alert( p[key] );
}

Nota: puede hacer esto sobre matrices, pero iterará sobre length y otras propiedades, también.

 14
Author: Richard Levasseur,
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
2012-11-03 21:46:04

Es interesante que las personas en estas respuestas hayan tocado tanto Object.keys() como for...of pero nunca las hayan combinado:

var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
    console.log(key + ':' + map[key]);

No puedes simplemente for...of un Object porque no es un iterador, y for...indexo .forEach() ing el Object.keys() es feo/ineficiente.
Me alegro de que la mayoría de la gente se abstenga de for...in (con o sin verificar .hasOwnProperty()) ya que también es un poco desordenado, por lo que aparte de mi respuesta anterior, estoy aquí para decir...


Puede hacer asociaciones de objetos comunes iterar! Comportarse como Map s con el uso directo de la fantasía for...of
DEMO trabajando en Chrome y FF (supongo que solo ES6)

var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
    //key:value
    console.log(pair[0] + ':' + pair[1]);

//or
for (let [key, value] of ordinaryObject)
    console.log(key + ':' + value);

Siempre y cuando incluyas mi cuña abajo:

//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
    var keys = Object.keys(this)[Symbol.iterator]();
    var obj = this;
    var output;
    return {next:function() {
        if (!(output = keys.next()).done)
            output.value = [output.value, obj[output.value]];
        return output;
    }};
};

Sin tener que crear un objeto de mapa real que no tenga el azúcar sintáctico agradable.

var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
    console.log(pair[0] + ':' + pair[1]);

De hecho, con esta cuña, si aún quería aprovechar las otras funcionalidades de Map (sin shimming todas) pero aún quería usar el objeto neat notación, ya que los objetos ahora son iterables, ¡ahora solo puede hacer un mapa a partir de él!

//shown in demo
var realMap = new Map({well:'hello', there:'!'});

Para aquellos que no les gusta calzar, o meterse con prototype en general, siéntanse libres de hacer la función en window en su lugar, llamándola algo como getObjIterator() entonces;

//no prototype manipulation
function getObjIterator(obj) {
    //create a dummy object instead of adding functionality to all objects
    var iterator = new Object();

    //give it what the shim does but as its own local property
    iterator[Symbol.iterator] = function() {
        var keys = Object.keys(obj)[Symbol.iterator]();
        var output;

        return {next:function() {
            if (!(output = keys.next()).done)
                output.value = [output.value, obj[output.value]];
            return output;
        }};
    };

    return iterator;
}

Ahora solo puedes llamarlo como una función ordinaria, nada más se ve afectado

var realMap = new Map(getObjIterator({well:'hello', there:'!'}))

O

for (let pair of getObjIterator(ordinaryObject))

No hay razón para que eso no funcione.

Bienvenido a la futuro.

 14
Author: Hashbrown,
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-06-16 03:28:59

Objeto.keys (obj) : Array

Recupera todas las claves con valor de cadena de todas las propiedades propias enumerables (no heredadas).

Por lo tanto, da la misma lista de claves que pretende al probar cada clave de objeto con hasOwnProperty. No necesita esa operación de prueba adicional que y Object.keys( obj ).forEach(function( key ){}) se supone que es más rápido. Vamos a probarlo:

var uniqid = function(){
			var text = "",
					i = 0,
					possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
			for( ; i < 32; i++ ) {
					text += possible.charAt( Math.floor( Math.random() * possible.length ) );
			}
			return text;
		}, 
		CYCLES = 100000,
		obj = {}, 
		p1,
		p2,
		p3,
		key;

// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
	obj[ uniqid() ] = new Date()
});

// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
	var waste = obj[ key ];
});

p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");

// Approach #2
for( key in obj ) {
	if ( obj.hasOwnProperty( key ) ) {
		var waste = obj[ key ];
	}
}

p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");

En mi Firefox tengo los siguientes resultados

  • Objeto.enfoque de claves tomó 40.21101451665163 milisegundo.
  • for...in/hasOwnProperty el enfoque tomó 98.26163508463651 milisegundos.

PS. en Chrome la diferencia aún mayor http://codepen.io/dsheiko/pen/JdrqXa

PS2: En ES6 (ECMAScript 2015) puede iterar objeto iterable mejor:

let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
    console.log(pair);
}

// OR 
let map = new Map([
    [false, 'no'],
    [true,  'yes'],
]);
map.forEach((value, key) => {
    console.log(key, value);
});
 12
Author: Dmitry Sheiko,
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-06-22 11:33:26

Aquí hay otro método para iterar a través de un objeto.

   var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};


Object.keys(p).forEach(key => { console.log(key, p[key]) })
 9
Author: Harsh Patel,
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-12-20 04:42:57

El método Object.keys() devuelve una matriz de las propiedades enumerables propias de un objeto dado. Lea más sobre esto aquí

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
 8
Author: George Bailey,
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-11-16 21:22:52

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " = " + p[key]);
    }
}
<p>
  Output:<br>
  p1 = values1<br>
  p2 = values2<br>
  p3 = values3
</p>
 8
Author: ParaMeterz,
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-03-19 14:08:57

Puede agregar una función simple forEach a todos los objetos, para que pueda recorrer automáticamente cualquier objeto:

Object.defineProperty(Object.prototype, 'forEach', {
    value: function (func) {
        for (var key in this) {
            if (!this.hasOwnProperty(key)) {
                // skip loop if the property is from prototype
                continue;
            }
            var value = this[key];
            func(key, value);
        }
    },
    enumerable: false
});

Para aquellas personas que no les gusta el " para ... en "-método:

Object.defineProperty(Object.prototype, 'forEach', {
    value: function (func) {
        var arr = Object.keys(this);
        for (var i = 0; i < arr.length; i++) {
            var key = arr[i];
            func(key, this[key]);
        }
    },
    enumerable: false
});

Ahora, puedes llamar simplemente:

p.forEach (function(key, value){
    console.log ("Key: " + key);
    console.log ("Value: " + value);
});

Si no desea obtener conflictos con otros métodos forEach, puede nombrarlo con su nombre único.

 7
Author: Biber,
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-11-28 08:25:45

Solo código JavaScript sin dependencias:

var p = {"p1": "value1", "p2": "value2", "p3": "value3"};
keys = Object.keys(p);   // ["p1", "p2", "p3"]

for(i = 0; i < keys.length; i++){
  console.log(keys[i] + "=" + p[keys[i]]);   // p1=value1, p2=value2, p3=value3
}
 5
Author: mohamed-ibrahim,
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-06-16 17:34:48

Los bucles pueden ser bastante interesantes cuando se usa JavaScript puro. Parece que solo ECMA6 (Nueva especificación de JavaScript de 2015) tiene los bucles bajo control. Desafortunadamente mientras escribo esto, tanto los navegadores como el popular entorno de desarrollo integrado (IDE) todavía están luchando para soportar completamente las nuevas campanas y silbidos.

De un vistazo aquí es cómo se ve un bucle de objetos JavaScript antes de ECMA6:

for (var key in object) {
  if (p.hasOwnProperty(key)) {
    var value = object[key];
    console.log(key); // This is the key;
    console.log(value); // This is the value;
  }
}

También, sé que esto está fuera de alcance con esta pregunta, pero en 2011, ECMAScript 5.1 agregó el método forEach solo para Arrays que básicamente creó una nueva forma mejorada de recorrer los arrays sin dejar objetos no iterables con el antiguo bucle for detallado y confuso. Pero la parte extraña es que este nuevo método forEach no soporta break lo que llevó a todo tipo de problemas.

Básicamente en 2011, no hay una forma sólida real de bucle en JavaScript que no sea lo que muchas bibliotecas populares (jQuery, Underscore, etc. decidió re-implementar.

A partir de 2015, ahora tenemos una mejor manera fuera de la caja de bucle (y romper) cualquier tipo de objeto (incluyendo matrices y cadenas). Así es como se verá un bucle en JavaScript cuando la recomendación se convierta en corriente principal:

for (let [key, value] of Object.entries(object)) {
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

Tenga en cuenta que la mayoría de los navegadores no admitirán el código anterior a partir del 18 de junio de 2016. Incluso en Chrome necesita habilitar esta bandera especial para que funcione: chrome://flags/#enable-javascript-harmony

Hasta que esto se convierta en el nuevo estándar, el antiguo método todavía se puede utilizar pero también hay alternativas en bibliotecas populares o incluso alternativas ligeras para aquellos que no están utilizando ninguna de estas bibliotecas.

 5
Author: Nicolas Bouvrette,
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-06-18 12:55:33

Haría esto en lugar de verificar obj.hasOwnerProperty dentro de cada bucle for ... in.

var obj = {a : 1};
for(var key in obj){
    //obj.hasOwnProperty(key) is not needed.
    console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
    throw new Error("Please don't extend the native object");
}
 4
Author: Lewis,
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-11-10 10:04:59

Si desea iterar sobre propiedades no enumerables también, puede utilizar Object.getOwnPropertyNames(obj) para devolver un array de todas las propiedades (enumerables o no) encontradas directamente sobre un objeto dado.

var obj = Object.create({}, {
  // non-enumerable property
  getFoo: {
    value: function() { return this.foo; },
    enumerable: false
  }
});

obj.foo = 1; // enumerable property

Object.getOwnPropertyNames(obj).forEach(function (name) {
  document.write(name + ': ' + obj[name] + '<br/>');
});
 3
Author: Dheeraj V.S.,
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-11-11 05:26:12

Si alguien necesita recorrer arrayObjects con la condición :

var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];

for (var i=0; i< arrayObjects.length; i++) {
  console.log(arrayObjects[i]);
  
  for(key in arrayObjects[i]) {      
    
      if (key == "status" && arrayObjects[i][key] == "good") {
        
          console.log(key + "->" + arrayObjects[i][key]);
      }else{
          console.log("nothing found");
      }
   }
}
 3
Author: Tadas V.,
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-07-22 03:48:23

Teniendo en cuenta ES6 me gustaría añadir mi propia cuchara de azúcar y proporcionar un enfoque más para iterar sobre las propiedades del objeto.

Dado que el objeto JS simple no es iterable recién salido de la caja, no podemos usar el bucle for..of para iterar sobre su contenido. Pero nadie puede detenernos para hacerlo iterable.

Vamos a tener book objeto.

let book = {
  title: "Amazing book",
  author: "Me",
  pages: 3
}

book[Symbol.iterator] = function(){

  let properties = Object.keys(this); // returns an array with property names
  let counter = 0;
  let isDone = false;

  let next = () => {
    if(counter >= properties.length){
      isDone = true;
    }
    return { done: isDone, value: this[properties[counter++]] }
  }

  return { next };
}

Ya que lo hemos hecho podemos usarlo de esta manera:

for(let pValue of book){
  console.log(pValue);
}
------------------------
Amazing book
Me
3

O si conoces el poder de ES6 generadores , por lo que ciertamente puede hacer que el código anterior sea mucho más corto.

book[Symbol.iterator] = function *(){

  let properties = Object.keys(this);
  for (let p of properties){
    yield this[p];
  }

}

Claro, puede aplicar este comportamiento a todos los objetos con hacer Object iterable en el nivel prototype.

Object.prototype[Symbol.iterator] = function() {...}

Además, los objetos que cumplen con el protocolo iterable se pueden usar con el nuevo operador ES2015 feature spread, por lo que podemos leer los valores de las propiedades de los objetos como una matriz.

let pValues = [...book];
console.log(pValues);
-------------------------
["Amazing book", "Me", 3]

O puedes usar desestructuración asignación:

let [title, , pages] = book; // notice that we can just skip unnecessary values
console.log(title);
console.log(pages);
------------------
Amazing book
3

Usted puede comprobar hacia fuera JSFiddle con todo el código que he proporcionado anteriormente.

 3
Author: Artyom Pranovich,
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-09-02 13:56:17

En el último script ES, puedes hacer algo como esto:

Object.entries(p);
 3
Author: Ankit,
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-09-11 05:55:01

    var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]
for(var value in p) {
    for (var key in value) {
        if (p.hasOwnProperty(key)) {
            console.log(key + " -> " + p[key]);
        }
    }
}
 3
Author: senthil,
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-09-14 17:51:00

En ES6 tenemos símbolos bien conocidos para exponer algunos métodos previamente internos, puede usarlo para definir cómo funcionan los iteradores para este objeto:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3",
    *[Symbol.iterator]() {
        yield *Object.keys(this);
    }
};

[...p] //["p1", "p2", "p3"]

Esto dará el mismo resultado que usar for...in es6 loop.

for(var key in p) {
    console.log(key);
}

Pero es importante conocer las capacidades que ahora tiene usando es6!

 2
Author: Bamieh,
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-09-20 09:04:34

Un objeto se convierte en un iterador cuando implementa el .método next ()

const james = {
name: 'James',
height: `5'10"`,
weight: 185,

[Symbol.iterator]() {
let properties = []
for (let key of Object.keys(james)){
     properties.push(key);
 }

index = 0;
return {
        next: () => {
            let key = properties[index];
            let value = this[key];
            let done = index >= properties.length - 1 ;
            index++;
            return { key, value, done };
        }
    };
  }

};


const iterator = james[Symbol.iterator]();

console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
 2
Author: Dan Alboteanu,
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-11-13 16:05:12

Desde ES06 puede obtener los valores de un objeto como matriz con

let arrValues = Object.values( yourObject) ;

Devuelve la matriz an de los valores del objeto y no extrae valores del prototipo!!

Objeto MDN DOCS.valores()

Y para las llaves (allready answerd antes de mí aquí )

let arrKeys   = Object.keys(yourObject);
 2
Author: yehonatan yehezkel,
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-22 15:41:26

Si desea iterar solo sobre propiedades, use una de las respuestas anteriores, sin embargo, si desea iterar sobre todo, incluidas las funciones, entonces es posible que desee usar Object.getOwnPropertyNames (obj)

for (let o of Object.getOwnPropertyNames(Math)) {
  console.log(o);
}

A veces uso esto para probar rápidamente todas las funciones en objetos con entradas y salidas simples.

 1
Author: Matas Vaitkevicius,
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-02-07 11:22:18

Tuve un problema similar al usar Angular, aquí está la solución que he encontrado.

Paso 1. Obtiene todas las claves del objeto. usando Objeto.claves. Este método devuelve una matriz de las propiedades enumerables propias de un objeto dado.

Paso 2. Cree una matriz vacía. Esto es un donde todas las propiedades van a vivir, ya que su nuevo lazo ngFor va a apuntar a esta matriz, tenemos que atraparlos a todos. Paso 3. Iterar lanzar todas las teclas, y empujar cada uno en el array que ha creado. Así es como se ve en código.

    // Evil response in a variable. Here are all my vehicles.
let evilResponse = { 
  "car" : 
    { 
       "color" : "red",
       "model" : "2013"
    },
   "motorcycle": 
    { 
       "color" : "red",
       "model" : "2016"
    },
   "bicycle": 
    { 
       "color" : "red",
       "model" : "2011"
    }
}
// Step 1. Get all the object keys.
let evilResponseProps = Object.keys(evilResponse);
// Step 2. Create an empty array.
let goodResponse = [];
// Step 3. Iterate throw all keys.
for (prop of evilResponseProps) { 
    goodResponse.push(evilResponseProps[prop]);
}

Aquí hay un enlace al post original. https://medium.com/@papaponmx/looping-over-object-properties-with-ngfor-in-angular-869cd7b2ddcc

 0
Author: Jaime Rios,
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-10-10 18:57:33