for array javascript jquery arrays

array - for javascript



El bucle de JavaScript sobre la entrada crea una matriz de objetos (7)

En este caso, debe usar un controlador de eventos para cambiar los valores de cualquier input o debe proporcionar algunos valores iniciales a estas entradas.

También puede iterar como se muestra a continuación para obtener el resultado deseado.

var dataArray = []; var data = {}; $("#time").find(''input'').each(function(i) { if(i%2 === 0){ data={}; data[this.name] = this.value; } else{ data[this.name] = this.value; dataArray.push(data); } }); console.log(dataArray);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="time"> <input type="text" name="from" placeholder="12:00 AM" value="12:00 AM" /> <input type="text" name="to" placeholder="12:30 AM" value="12:30 AM" /> <input type="text" name="from" placeholder="13:00 AM" value="13:00 AM" /> <input type="text" name="to" placeholder="13:30 AM" value="13:30 AM" /> </div> <span id="output"></span>

Estoy intentando hacer un bucle sobre los elementos de entrada en div, para crear una matriz de objetos

<div id="time"> <input type="text" name="from" placeholder="12:00 AM" /> <input type="text" name="to" placeholder="12:30 AM" /> <input type="text" name="from" placeholder="13:00 AM" /> <input type="text" name="to" placeholder="13:30 AM" /> </div>

Estoy tratando de crear la siguiente matriz de objetos.

unavailability: [ { from: ''12:00'', to: ''12:30'' }, { from: ''13:00'', to: ''13:30'' } ]

Esto es lo que he intentado hasta ahora, pero el resultado es bastante diferente.

var dataArray = [] $("#time").find(''input'').each(function() { var data = {}; data[this.name] = this.value dataArray.push(data); }); console.log(dataArray)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="time"> <input type="text" name="from" placeholder="12:00 AM" /> <input type="text" name="to" placeholder="12:30 AM" /> <input type="text" name="from" placeholder="13:00 AM" /> <input type="text" name="to" placeholder="13:30 AM" /> </div>

JSFiddle


En lugar de iterar sobre cada entrada, debe iterar sobre cada elemento de entrada alternativo con un atributo de nombre igual a la forma. Luego, cree la información JSON para el elemento sobre el que está iterando y el siguiente elemento de entrada de hermano inmediato.

Además, las 12.30 no es el valor del elemento, su marcador de posición. Debe reemplazar el valor con un marcador de posición:

$("#time").find(''input[name="from"]'').each(function() { var data = {}; data[this.name] = this.placeholder; var nextInput = $(this).next()[0]; data[nextInput .name] = nextInput.placeholder; dataArray.push(data); });

Demo de trabajo

La mejor manera de lograr esto es usar la función jQuery .map() que devuelve el objeto JSON junto con .get() para crear una matriz de objetos JSON:

var dataArray = $("#time").find(''input[name="from"]'').map(function() { var nextInput = $(this).next()[0]; var jo = {}; jo[this.name]=this.placeholder;jo[nextInput.name] = nextInput.placeholder return jo; }).get();

var dataArray = $("#time").find(''input[name="from"]'').map(function() { var nextInput = $(this).next()[0]; var jo = {}; jo[this.name]=this.placeholder;jo[nextInput.name] = nextInput.placeholder return jo; }).get(); console.log(dataArray)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="time"> <input type="text" name="from" placeholder="12:00 AM" /> <input type="text" name="to" placeholder="12:30 AM" /> <input type="text" name="from" placeholder="13:00 AM" /> <input type="text" name="to" placeholder="13:30 AM" /> </div>


En mi respuesta, empujo un nuevo elemento a la matriz solo si this.name === "from" . Si this.name === "to" , agrego una nueva propiedad al último elemento this.name === "to" , y finalmente tenemos 2 objetos en matriz y 2 propiedades en cada objeto:

$("#btn").click(doStuff); function doStuff() { var dataArray = [] var newArrayLength; $("#time").find(''input'').each(function() { if (this.name === "from") { var data = {}; data[this.name] = this.value newArrayLength = dataArray.push(data); } else if (this.name === "to") { dataArray[newArrayLength - 1][this.name] = this.value; } }); console.log(dataArray); }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="time"> <input type="text" name="from" placeholder="12:00 AM" /> <input type="text" name="to" placeholder="12:30 AM" /> <input type="text" name="from" placeholder="13:00 AM" /> <input type="text" name="to" placeholder="13:30 AM" /> </div> <span id="output"></span> <button id="btn">Click</button>

https://jsfiddle.net/ss725ere/2/


Lo habría resuelto con FormData. Significa menos navegación DOM y menos posibilidades de hacer algo mal si cambias el marcado más adelante. Esto también significa que tendría que cambiar su elemento div a un elemento de formulario (a menos que lo tenga en algún lugar más arriba, en ese caso podría usar ese elemento de formulario en el constructor y mantener el elemento div):

// Get a formdata instance var fd = new FormData(time) // Get all values var from = fd.getAll(''from'') var to = fd.getAll(''to'') // Transform var unavailable = from.map((from, i) => ({ from, to: to[i] })) console.log({unavailable})

<form id="time"> <input type="text" name="from" placeholder="12:00 AM" value="12:00" /> <input type="text" name="to" placeholder="12:30 AM" value="12:30" /> <input type="text" name="from" placeholder="13:00 AM" value="13:00" /> <input type="text" name="to" placeholder="13:30 AM" value="13:30" /> </form>

Por cierto, estás mezclando 12/24 horas (13:00). Tal vez debería escribirse como 1:00 pm (?).

También habría cambiado el tipo a type="time" para evitar errores. Le da un buen selector de tiempo y normaliza el valor si el usuario ingresa un valor de 12 o 24 horas. También podría usar step / min / max / required para una mejor validación si lo necesitara


Puede iterar sobre todos los elementos que tienen un valor de atributo de nombre a from . Para obtener el valor a, use el método next() de jQuery.

Utilice el método .val() para obtener el valor del elemento.

$(''#submit'').click(function() { var data = []; $(''#time input[name="from"]'').each(function() { data.push({ from: $(this).val(), to: $(this).next().val() }); }); console.log(data); });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Enter times in the below textboxes <div id="time"> <input type="text" name="from" placeholder="12:00 AM" /> <input type="text" name="to" placeholder="12:30 AM" /> <input type="text" name="from" placeholder="13:00 AM" /> <input type="text" name="to" placeholder="13:30 AM" /> </div> <button id="submit">Submit</button>


Puedes hacerlo de la siguiente manera:

var unavailability = []; $(''#time input[name=from]'').each(function(i, input){ unavailability.push({ from: $(this).attr(''placeholder'').split('' '')[0], to: $(this).next().attr(''placeholder'').split('' '')[0] }); }); console.log(unavailability);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="time"> <input type="text" name="from" placeholder="12:00 AM" /> <input type="text" name="to" placeholder="12:30 AM" /> <input type="text" name="from" placeholder="13:00 AM" /> <input type="text" name="to" placeholder="13:30 AM" /> </div>


var dataArray = []; $("#time").find(''input[name="from"]'').each(function() { var data = {}; data.from = this.value; data.to = $(this).next().val(); dataArray.push(data); }); console.log(dataArray);

Violín actualizado