I'm retrofitting an open source project with some additional input fields. What I need to be able to do is get pairs of input fields as key/value pairs and push them to an array.
Ignoring aesthetics, the general gist is:
<input placeholder="Key1"> <input placeholder="Value1"> <!-- Pair 1 -->
<input placeholder="Key2"> <input placeholder="Value2"> <!-- Pair 2 -->
<input placeholder="Key3"> <input placeholder="Value3"> <!-- Pair 3 -->
How can I configure the input fields so they can be
# Example
<button>Add New Key/Value</button>
I then expect to be able to parse it to an array of maps like so:
let values = [
{key: "Key1", value: "Value1"},
]
At the moment I have a single static pair with id's set which I query
var key1 = trim( $('#key1').val() );
var value1 = trim( $('#value1').val() );
But this isn't scalable or allows itself to be dynamic.
Note: I can't implement a framework like Vue or React, as this is an existing codebase.
You can select all the inputs, then use Array.reduce.
In the reducer function, you can check whether the index is even or not. If it is, push to the array a new object with its key property set to the input's placeholder property. If not, set the array's last item's value property to the input's placeholder property.
const inputs = document.querySelectorAll('#form1 input')
const values = [...inputs].reduce((a,b,i) => {
if(i % 2 == 0){
a.push({key:b.placeholder})
}else{
a[a.length - 1].value = b.placeholder;
}
return a;
}, [])
console.log(values)
<form id="form1">
<input placeholder="Key1"> <input placeholder="Value1"> <!-- Pair 1 -->
<input placeholder="Key2"> <input placeholder="Value2"> <!-- Pair 2 -->
<input placeholder="Key3"> <input placeholder="Value3"> <!-- Pair 3 -->
</form>
Just wrap each pair in a containing element and map those containers returning an object for each container
const containers = document.querySelectorAll('.input-container')
const arr = [...containers].map(el => {
const inputs = el.querySelectorAll('input');
return {key: inputs[0].placeholder , value: inputs[1].placeholder}
})
console.log(arr)
<div class="input-container">
<input placeholder="Key1"> <input placeholder="Value1">
<!-- Pair 1 -->
</div>
<div class="input-container">
<input placeholder="Key2"> <input placeholder="Value2">
<!-- Pair 2 -->
</div>
<div class="input-container">
<input placeholder="Key3"> <input placeholder="Value3">
<!-- Pair 3 -->
</div>