Как из полученных данных из полей создать массив объектов?

Рейтинг: 0Ответов: 1Опубликовано: 20.03.2023

$('.send').on('click', function() {
  let prices = $('input[name="prices[]"]').map((i, e) => e.value).get();
  let amounts = $('input[name="amounts[]"]').map((i, e) => e.value).get();
  
  console.log(prices, amounts);
  
  // Как получить данные из полей в таком виде?
  // Может быть больше 2
  let orders = [
    { price: 1000, amount: 10 },
    { price: 2000, amount: 20 },
  ];

  // Для дальнейшей отправки на сервер по ajax
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input type="text" name="prices[]" value="1000" placeholder="Price">
  <input type="text" name="amounts[]" value="10" placeholder="Amount">
</div>
<div>
  <input type="text" name="prices[]" value="2000" placeholder="Price">
  <input type="text" name="amounts[]" value="20" placeholder="Amount">
</div>
<button type="submit" class="send">Send</button>

Ответы

▲ 1Принят

Если уж совсем просто, то в данном случае можно так:

 let orders = prices.map((item,index) => {
    return {'prices':+item,'amount': +amounts[index]};
  });