Cómo crear json por JavaScript para loop?


Tengo array de select tag.

<select id='uniqueID' name="status">
      <option value="1">Present</option>
      <option value="2">Absent</option>
 </select>

Y quiero crear un objeto json que tenga dos campos 'uniqueIDofSelect y OptionValue' en JavaScript.

Utilizo getElementsByName("status") y lo itero.

EDITAR

Necesito poner como

[{"selectID":2,"OptionValue":"2"},
{"selectID":4,"optionvalue":"1"}]

Y así sucesivamente...

Author: Brett DeWoody, 2009-05-28

5 answers

Por lo que entiendo de su solicitud, esto debería funcionar:

<script>
//  var status  = document.getElementsByID("uniqueID"); // this works too
var status  = document.getElementsByName("status")[0];
var jsonArr = [];

for (var i = 0; i < status.options.length; i++) {
    jsonArr.push({
        id: status.options[i].text,
        optionValue: status.options[i].value
    });
}
</script>
 164
Author: donohoe,
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-12-20 22:18:13
var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}
 41
Author: Josh Stodola,
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
2009-05-28 14:36:38

Si desea un único objeto JavaScript como el siguiente:

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }

(donde la opción 2, "Ausente", es la selección actual) entonces el siguiente código debería producirlo:

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }

Si desea una matriz de todos estos objetos (no solo el seleccionado), use el código de michael pero cambie status.options[i].text por status.id.

Si desea una cadena que contenga una representación JSON del objeto seleccionado, use esto en su lugar:

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }
 8
Author: system PAUSE,
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-05-23 11:54:15

Si quiero crear un objeto JavaScript a partir de una cadena generada por for loop, entonces me gustaría JSON a Object approach. Generaría una cadena JSON iterando para loop y luego usaría cualquier marco JavaScript popular para evaluar JSON a Object.

He utilizado Prototype JavaScript Framework. Tengo dos matriz con claves y valores. Iteré a través del bucle for y generé una cadena JSON válida. Uso la función evalJSON() para convertir una cadena JSON a JavaScript objeto.

Aquí está el código de ejemplo. Prueba en tu Consola FireBug

var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];

var json = "{ ";
for(var i = 0; i < key.length; i++) {
    (i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);
 3
Author: Gaurang Jadia,
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-24 21:35:19

Su pregunta es bastante difícil de decodificar, pero voy a tratar de tomar una puñalada en ella.

Usted dice:

Quiero crear un objeto json con dos campos uniqueIDofSelect y optionValue en javascript.

Y luego dices:

Necesito una salida como

[{"selectID":2,"optionValue":"2"},
{"selectID":4,"optionvalue":"1"}]

Bueno, esta salida de ejemplo no tiene el campo llamado uniqueIDofSelect, sólo tiene optionValue.

De todos modos, usted está pidiendo la matriz de objeto...

Luego en el comentario a la respuesta de michaels dices:

Crea una matriz de objetos json. pero solo necesito un objeto json.

¿Entonces no quieres una matriz de objetos?

¿Qué quieres entonces?

Por favor, decídete.

 0
Author: Rene Saarsoo,
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
2009-05-30 10:06:51