I have a collection of inputs
<input type="text" name="item" id="item" value="Name"> <input type="number" name="unit_price" id="unit_price" value="100"> <input type="number" name="qty" id="qty" value="2"> <input type="number" name="discount" id="discount" value="0"> <input type="text" name="item" id="item" value="Name 2"> <input type="number" name="unit_price" id="unit_price" value="200"> <input type="number" name="qty" id="qty" value="5"> <input type="number" name="discount" id="discount" value="10">
I’m trying to loop through all of these inputs to create an object with keys exactly the same as names in my inputs and add those values as values. So my steps are:
let arr = [] inputs.forEach((elem) => { console.log(elem.value) arr.push({ 'item': elem.value, 'unit_price': elem.value, 'qty': elem.value, 'discount': elem.value }); })
EDITED the expected output should look like this:
arr = [{ 'item': 'Name', 'unit_price': '100', 'qty': '2', 'discount': '0', }, { 'item': 'Name 2', 'unit_price': '200', 'qty': '5', 'discount': '10' } ]
Advertisement
Answer
You can iterate over the input elements in chunks of 4.
let inputs = document.querySelectorAll('input'); let res = []; let names = ['item', 'unit_price', 'qty', 'discount']; for (let i = 0; i < inputs.length; i += names.length) res.push(names.reduce((acc, curr, j) => (acc[curr] = inputs[i + j].value, acc), {})); console.log(res);
<input type="text" name="item" id="item" value="Name"> <input type="number" name="unit_price" id="unit_price" value="100"> <input type="number" name="qty" id="qty" value="2"> <input type="number" name="discount" id="discount" value="0"> <input type="text" name="item" id="item" value="Name 2"> <input type="number" name="unit_price" id="unit_price" value="200"> <input type="number" name="qty" id="qty" value="5"> <input type="number" name="discount" id="discount" value="10">