Cómo recorrer un array que contiene objetos y acceder a sus propiedades
Quiero recorrer los objetos contenidos en un array y cambiar las propiedades de cada uno. Si hago esto:
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j]);
}
La consola debería mostrar todos los objetos de la matriz, ¿verdad? Pero de hecho solo muestra el primer objeto. si la consola de registro de la matriz fuera del bucle, todos los objetos aparecen por lo que definitivamente hay más allí.
De todos modos, aquí está el siguiente problema. Cómo puedo acceder, por ejemplo Object1.x en la matriz, usando el bucle?
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j.x]);
}
Esto devuelve "indefinido."De nuevo el registro de consola fuera del bucle me dice que todos los objetos tienen valores para "x". ¿Cómo puedo acceder a estas propiedades en el bucle?
Me recomendaron en otro lugar usar matrices separadas para cada una de las propiedades, pero quiero asegurarme de haber agotado esta vía primero.
¡Gracias!
12 answers
Use forEach es una función de matriz incorporada. Array.forEach()
:
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
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-26 08:59:51
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
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-09 10:57:35
En ECMAScript 2015 también conocido como ES6, puede usar un para..of loop para hacer un bucle sobre una matriz de objetos.
for (let item of items) {
console.log(item); // Will display contents of the object inside the array
}
En el momento de publicar esta respuesta, el soporte es bastante inexistente para Internet Explorer, pero a través del uso de un transpiler como Traceur o Babel, puede usar nuevas características de Javascript como esta sin tener que preocuparse realmente por qué navegadores soportan qué.
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-29 02:11:28
Aquí hay un ejemplo de cómo puedes hacerlo:)
var students = [
{
name : "Mike",
track: "track-a",
achievements: 23,
points : 400,
},
{
name : "james",
track: "track-a",
achievements: 2,
points : 21,
},
]
students.forEach(myFunction);
function myFunction (item, index) {
for( var key in item ) {
console.log(item[key])
}
}
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-05 10:32:49
Algunos casos de uso de bucle a través de un array en la forma de programación funcional en JavaScript:
1. Simplemente haga un bucle a través de una matriz
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
Nota: Array.prototipo.forEach () no es una forma funcional estrictamente hablando, ya que la función que toma como parámetro de entrada no debe devolver un valor, que por lo tanto no puede ser considerada como una función pura.
2. Compruebe si alguno de los elementos de un array pasa una prueba
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
3. Transformar a un nuevo array
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
Nota: El método map() crea una nueva matriz con los resultados de llamar a una función proporcionada en cada elemento de la matriz que llama.
4. Suma una propiedad particular, y calcula su promedio
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
5. Crear un nuevo array basado en el original pero sin modificarlo
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
6. Cuente el número de cada categoría
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
7. Recuperar un subconjunto de una matriz basada en criterios particulares
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
Nota: El filtro() método crea una nueva matriz con todos los elementos que pasan la prueba implementada por la función proporcionada.
8. Ordenar una matriz
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
9. Buscar un elemento en un array
const people = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const john = people.find(person => person.name === 'john');
console.log(john);
La Matriz.prototipo.el método find () devuelve el valor del primer elemento de la matriz que satisface las pruebas proporcionadas función.
Referencias
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-29 10:33:31
myArray[j.x]
es lógicamente incorrecto.
Use (myArray[j].x);
en su lugar
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
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-18 17:57:00
El bucle a través de una matriz de objetos es una funcionalidad bastante fundamental. Esto es lo que funciona para mí.
var person = [];
person[0] = {
firstName : "John",
lastName : "Doe",
age : 60
};
var i, item;
for (i = 0; i < person.length; i++) {
for (item in person[i]) {
document.write(item + ": " + person[i][item] + "<br>");
}
}
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-05-15 04:39:53
Es realmente simple usar el método forEach desde ES5+. Puede cambiar directamente cada propiedad de cada objeto en su matriz.
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
Si desea acceder a una propiedad específica en cada objeto:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
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-03-23 16:18:58
Aquí hay otra forma de iterar a través de una matriz de objetos (debe incluir la biblioteca jQuery en su documento para estos).
$.each(array, function(element) {
// do some operations with each element...
});
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 15:55:01
Esto funcionaría. Looping thorough array (yourArray). Luego recorre las propiedades directas de cada objeto (eachObj) .
yourArray.forEach( function (eachObj){
for (var key in eachObj) {
if (eachObj.hasOwnProperty(key)){
console.log(key,eachObj[key]);
}
}
});
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-12-26 11:13:52
Iteración de objetos de matriz, usando jQuery, (utilice el segundo parámetro para imprimir la cadena).
$.each(array, function(index, item) {
console.log(index, item);
});
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-04-25 04:53:54
La respuesta aceptada usa la función normal. Así que publicando el mismo código con una ligera modificación usando la función de flecha en forEach
yourArray.forEach((arrayItem) => {
var x = arrayItem.prop1 + 2;
console.log(x);
});
También en $.cada uno puede utilizar la función de flecha como a continuación
$.each(array, (index, item) => {
console.log(index, item);
});
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-05 17:35:26