Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript loop over input creates an array of objects

I'm trying to loop over input elements in div, to create an array of objects

<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>

I'm trying to create the following array of objects.

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

Here is what I have tried so far, but result is quite different.

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

like image 780
Deano Avatar asked Jan 17 '18 06:01

Deano


People also ask

Can you have an array of objects in JavaScript?

Creating an array of objects We can represent it as an array this way: let cars = [ { "color": "purple", "type": "minivan", "registration": new Date('2017-01-03'), "capacity": 7 }, { "color": "red", "type": "station wagon", "registration": new Date('2018-03-03'), "capacity": 5 }, { ... }, ... ]

Can you loop through an array in JavaScript?

If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array.

Can we use for loop for object in JavaScript?

Introduction to looping through objects using javascript If you have an array that is considered to be an object in javascript, you can't loop through the array using map(), forEach(), or a for..of loop.


1 Answers

You may iterate over all the elements having name attribute value as from. To get the to value, use next() method of jQuery.

Use .val() method to get the value of item.

$('#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>
like image 79
Tushar Avatar answered Oct 17 '22 10:10

Tushar