Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
Array with subarray loop Javascript

Is it possible to create an array and loop through it in JavaScript like below?

<?php
$options = array(
    'color' => array('blue', 'yellow', 'white'), 
    'size' => array('39', '40', '41'),
);

foreach($options as $option => $values){
    echo $option.'<br>';
    foreach($values as $value){
        echo $value.' ';
    }
    echo '<br>';
}
?>

I checked the internet but I can not find a good example.

Thanks for helping!

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Exactly

let options = {
    color: ['blue', 'yellow', 'white'],
    size: [39, 40, 41]
};

You have three ways to do this:

FOR

for (option in options) {
    console.log(option);
    var values = options[option];
    for (let i = 0, len = values.length, value = values[i]; i < len; value = values[++i]) {
        console.log(value);
    }
}

ARRAY FOREACH

for (option in options) {
    console.log(option);
    options[option].forEach(value => {
        console.log(value);
    });
}

Easiest way: jQuery

$.each(options, (option, values) => {
    console.log(option);
    $.each(values, (key, value) => {
        console.log(value);
    });
});
about 4 years ago · Santiago Trujillo Denunciar

0

Arrays in javascript have integer keys (indexes). You can use an object as you need to store string keys on the parent level and the values can be arrays as they don't have any string keys

const options = {
  color: ['blue', 'yellow', 'white'],
  size: ['39', '40', '41'],
}

Object.entries(options).forEach(([key, value]) => {
  console.log(key)
  value.forEach(el => console.log(el))
})

about 4 years ago · Santiago Trujillo Denunciar

0

If I understand you correctly you want a javascript equivalent to the php code you've given?

If so, it could be achieved the following way:

let options = {
    color: ['blue', 'yellow', 'white'],
    size: [39, 40, 41]
};

for(option of Object.keys(options)) {
    console.log(option);
    
    for(value of options[option]) {
        console.log(value);
    }
}

this is not exactly the same as your php code, but the loop works in a similar way.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda