¿Cómo obtener todos los valores de propiedades de un objeto Javascript (sin conocer las claves)?


Si hay un objeto Javascript:

var objects={...};

Supongamos que tiene más de 50 propiedades, sin conocer los nombres de las propiedades (es decir, sin conocer las 'claves') ¿cómo obtener cada valor de propiedad en un bucle?

Author: ftor, 2011-09-05

20 answers

Usando un bucle simple for..in:

for(var key in objects) {
    var value = objects[key];
}
 399
Author: Tatu Ulmanen,
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-09-05 10:22:05

Dependiendo de los navegadores que tenga que soportar, esto se puede hacer de varias maneras. La abrumadora mayoría de los navegadores en el salvaje soporte ECMAScript 5 (ES5), pero tenga en cuenta que muchos de los ejemplos a continuación utilizan Object.keys, que no está disponible en IE .

ECMAScript 3 +

Si tiene que soportar versiones anteriores de IE, entonces esta es la opción para usted:

for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
        var val = obj[key];
        // use val
    }
}

El anidado if se asegura de que no enumere sobre propiedades en la cadena de prototipos del objeto(que es el comportamiento que casi con seguridad desea). Debe utilizar

Object.prototype.hasOwnProperty.call(obj, key) // ok

En lugar de

obj.hasOwnProperty(key) // bad

Porque ECMAScript 5+ le permite crear objetos sin prototipos con Object.create(null), y estos objetos no tendrán el método hasOwnProperty. Naughty code también puede producir objetos que anulan el método hasOwnProperty.

ECMAScript 5 +

Puede usar estos métodos en cualquier navegador que soporte ECMAScript 5 y superior. Estos obtenga valores de un objeto y evite enumerar sobre la cadena de prototipos. Donde obj es su objeto:

var keys = Object.keys(obj);

for (var i = 0; i < keys.length; i++) {
    var val = obj[keys[i]];
    // use val
}

Si quieres algo un poco más compacto o quieres tener cuidado con las funciones en bucles, entonces Array.prototype.forEach es tu amigo:

Object.keys(obj).forEach(function (key) {
    var val = obj[key];
    // use val
});

El siguiente método construye una matriz que contiene los valores de un objeto. Esto es conveniente para hacer un bucle.

var vals = Object.keys(obj).map(function (key) {
    return obj[key];
});

// use vals array

Si desea hacer que los que usan Object.keys sean seguros contra null (como for-in es), entonces puede hacer Object.keys(obj || {})....

Object.keys devuelve propiedades enumerables. Para iterar sobre objetos simples, esto suele ser suficiente. Si tiene algo con propiedades no enumerables con las que necesita trabajar, puede usar Object.getOwnPropertyNames en lugar de Object.keys.

ECMAScript 2015+ (A. K. A. ES6)

Los arrays son más fáciles de iterar con ECMAScript 2015. Puede usar esto para su ventaja cuando trabaja con valores uno por uno en un bucle:

for (const key of Object.keys(obj)) {
    const val = obj[key];
    // use val
}

Usando ECMAScript 2015 fat-arrow funciones, mapear el objeto a una matriz de valores se convierte en una línea:

const vals = Object.keys(obj).map(key => obj[key]);

// use vals array

ECMAScript 2015 introduce Symbol, instancias de las cuales se pueden usar como nombres de propiedad. Para obtener los símbolos de un objeto para enumerar, use Object.getOwnPropertySymbols (esta función es la razón Symbol no se puede usar para hacer propiedades privadas). La nueva API Reflect de ECMAScript 2015 proporciona Reflect.ownKeys, que devuelve una lista de nombres de propiedades (incluidos los no enumerables) y símbolos.

Comprensiones de matrices (no intente utilizar)

Las comprensiones de matrices fueron eliminadas de ECMAScript 6 antes de su publicación. Antes de su eliminación, una solución habría parecido:

const vals = [for (key of Object.keys(obj)) obj[key]];

// use vals array

ECMAScript 2017 +

ECMAScript 2016 agrega características que no afectan este tema. La especificación ECMAScript 2017 agrega Object.values y Object.entries. Ambos devuelven matrices (lo que sorprenderá a algunos dada la analogía con Array.entries). Object.values se puede utilizar tal cual o con un for-of bucle.

const values = Object.values(obj);

// use values array or:

for (const val of Object.values(obj)) {
    // use val
}

Si desea utilizar tanto la clave como el valor, entonces Object.entries es para usted. Produce una matriz llena de pares [key, value]. Puede usar esto tal cual, o (tenga en cuenta también la asignación de desestructuración ECMAScript 2015) en un bucle for-of:

for (const [key, val] of Object.entries(obj)) {
    // use key and val
}

Object.values shim

Finalmente, como se señala en los comentarios y por teh_senaus en otra respuesta, puede valer la pena usar uno de estos como una cuña. No se preocupe, lo siguiente no cambia el prototipo, solo agrega un método a Object (que es mucho menos peligroso). Usando las funciones fat-arrow, esto también se puede hacer en una línea:

Object.values = obj => Object.keys(obj).map(key => obj[key]);

Que ahora puedes usar como

// ['one', 'two', 'three']
var values = Object.values({ a: 'one', b: 'two', c: 'three' });

Si desea evitar el shimming cuando existe un nativo Object.values, entonces puede hacer:

Object.values = Object.values || (obj => Object.keys(obj).map(key => obj[key]));

Finalmente...

Tenga en cuenta los navegadores/versiones que necesita soportar. Lo anterior es correcto donde se implementan los métodos o las características del lenguaje. Por ejemplo, el soporte para ECMAScript 2015 se desactivó de forma predeterminada en V8 hasta hace poco, que impulsó navegadores como Chrome. Las características de ECMAScript 2015 deben evitarse hasta que los navegadores que desea admitir implementen las características que necesita. Si usas babel para compilar tu código a ECMAScript 5, entonces tienes acceso a todas las características de esta respuesta.

 917
Author: qubyte,
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-08-12 01:42:23

Aquí hay una función reutilizable para obtener los valores en una matriz. También tiene en cuenta los prototipos.

Object.values = function (obj) {
    var vals = [];
    for( var key in obj ) {
        if ( obj.hasOwnProperty(key) ) {
            vals.push(obj[key]);
        }
    }
    return vals;
}
 28
Author: teh_senaus,
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
2013-02-27 13:49:58

Si tiene acceso a subrayado.js, puedes usar el _.values funciona así:

_.values({one : 1, two : 2, three : 3}); // return [1, 2, 3]
 27
Author: jichi,
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-28 16:40:34

Si realmente quieres una matriz de Valores, encuentro esto más limpio que construir una matriz con un for ... en bucle.

ECMA 5.1 +

function values(o) { return Object.keys(o).map(function(k){return o[k]}) }

Vale la pena señalar que en la mayoría de los casos realmente no necesita una matriz de valores, será más rápido hacer esto:

for(var k in o) something(o[k]);

Esto itera sobre las claves del Objeto o. En cada iteración k se establece en una clave de o.

 14
Author: zzz,
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-05-03 14:07:21

ES5 Object.keys

var a = { a: 1, b: 2, c: 3 };
Object.keys(a).map(function(key){ return a[key] });
// result: [1,2,3]
 7
Author: MrBii,
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-28 16:42:37

Puedes recorrer las teclas:

foo = {one:1, two:2, three:3};
for (key in foo){
    console.log("foo["+ key +"]="+ foo[key]);
}

Producirá:

foo[one]=1
foo[two]=2
foo[three]=3
 5
Author: ariera,
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
2013-02-14 03:34:14

Para aquellos que se adaptaron temprano en la era de Cofescript, aquí hay otro equivalente para ello.

val for key,val of objects

Que puede ser mejor que esto porque el objects puede reducirse para ser escrito de nuevo y disminuir la legibilidad.

objects[key] for key of objects
 3
Author: Ch.Idea,
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-02-24 12:20:19

Utilice un polyfill como:

if(!Object.values){Object.values=obj=>Object.keys(obj).map(key=>obj[key])}

Luego use

Object.values(my_object)

3) ¡beneficio!

 3
Author: user40521,
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-12-26 13:28:18

Aparentemente, como aprendí recientemente, esta es la forma más rápida de hacerlo:

var objs = {...};
var objKeys = Object.keys(obj);
for (var i = 0, objLen = objKeys.length; i < objLen; i++) {
    // do whatever in here
    var obj = objs[objKeys[i]];
}
 2
Author: dylnmc,
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-10-01 13:09:01

Aquí hay una función similar a array_values () de PHP

function array_values(input) {
  var output = [], key = '';
  for ( key in input ) { output[output.length] = input[key]; }
  return output;
}

Aquí le mostramos cómo obtener los valores del objeto si está utilizando ES6 o superior:

Array.from(values(obj));
 0
Author: jaggedsoft,
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-22 23:09:12

Compatible con ES7 incluso algunos navegadores no lo soportan todavía

Dado , Object.values(<object>) será incorporado en ES7 &

Hasta que espere a que todos los navegadores lo soporten, puede envolverlo dentro de una función :

Object.vals=(o)=>(Object.values)?Object.values(o):Object.keys(o).map((k)=>o[k])

Entonces:

Object.vals({lastname:'T',firstname:'A'})
 // ['T','A']

Una vez que los navegadores sean compatibles con ES7, no tendrá que cambiar nada en su código.

 0
Author: Abdennour TOUMI,
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-27 21:07:59

Me doy cuenta de que estoy un poco tarde, pero aquí hay un cuña para el nuevo firefox 47 Object.values método

Object.prototype.values = Object.prototype.values || function(obj) {
  return this.keys(obj).map(function(key){
    return obj[key];
  });
};
 0
Author: Jamie,
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-28 16:51:31

Objeto.las entradas lo hacen de mejor manera.

  var dataObject = {"a":{"title":"shop"}, "b":{"title":"home"}}
 
   Object.entries(dataObject).map(itemArray => { 
     console.log("key=", itemArray[0], "value=", itemArray[1])
  })
 0
Author: Must keem,
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-19 06:43:42

A partir de ECMA2017:

Object.values(obj) obtendrá todos los valores de propiedad como una matriz.

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

 0
Author: ishandutta2007,
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-04 10:42:50

Use: Object.values(), pasamos un objeto como argumento y recibimos una matriz de los valores como valor devuelto.

Esto devuelve un array de un objeto dado con sus propios valores de propiedad enumerables. Obtendrá los mismos valores que usando el bucle for in pero sin las propiedades del Prototipo. Este ejemplo probablemente hará las cosas más claras:

function person (name) {
  this.name = name;
}

person.prototype.age = 5;

let dude = new person('dude');

for(let prop in dude) {
  console.log(dude[prop]);     // for in still shows age because this is on the prototype
}                              // we can use hasOwnProperty but this is not very elegant

// ES6 + 
console.log(Object.values(dude));
// very concise and we don't show props on prototype
 0
Author: Willem van der Veen,
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 14:34:50
var objects={...}; this.getAllvalues = function () {
        var vls = [];
        for (var key in objects) {
            vls.push(objects[key]);
        }
        return vls;
    }
 -1
Author: Sudarshan,
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
2013-05-20 05:34:44

En ECMAScript5 use

 keys = Object.keys(object);

De lo contrario, si su navegador no lo soporta, use el conocido for..in loop

for (key in object) {
    // your code here
}
 -3
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-09-05 10:56:50

Ahora uso Dojo Toolkit porque los navegadores más antiguos no son compatibles con Object.values.

require(['dojox/lang/functional/object'], function(Object) {
    var obj = { key1: '1', key2: '2', key3: '3' };
    var values = Object.values(obj);
    console.log(values);
});

Salida:

['1', '2', '3']
 -8
Author: rio,
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-28 16:48:49

Use

console.log(variable)

Y si usa Google Chrome, abra la consola usando Ctrl + Shift + j

Ir a > > Consola

 -10
Author: Puneet,
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
2014-05-13 09:29:26