After the user enters the values for column and value, this is how the data is being received:
[
[{
label: "Column",
value: "column1",
name: "01",
},
{
label: "Value",
value: "value1",
name: "02",
},
],
[{
label: "Column",
value: "column2",
name: "10",
},
{
label: "Value",
value: "value2",
name: "11",
},
],
];
But that's not how it can be saved to send the database, the way I need to send it is like this:
{
"column_names": {
"column1": "value1",
"column2": "value2"
}
}
Could you tell me how can I create an Object based on what the user types? But in the structure I showed in the second code snippet?
CodePudding user response:
The data structure provided by the OP can be seen as an array of object entries where each entry holds a tuple of key and value related meta data.
Thus a straightforward approach does reduce
the provided data into the desired record.
const receivedData = [
[{
label: "Column",
value: "column1",
name: "01",
}, {
label: "Value",
value: "value1",
name: "02",
}], [{
label: "Column",
value: "column2",
name: "10",
}, {
label: "Value",
value: "value2",
name: "11",
}],
];
const recordData = {
"column_names": receivedData
.reduce((data, [ keyData, valueData ]) => {
const key = keyData.value;
const { value } = valueData;
return Object.assign(data, { [key]: value });
}, {})
};
console.log({ recordData });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
CodePudding user response:
your expected result is object design based where you can group value by their names which is a bit more lengthy but if you wanted to improve object design to do same task i have a suggested code try this
use data
attribute on input fields with their name
then get all the values in one object with their corresponding key names see an example below
function getData(root){
const Els = root.querySelectorAll("[data]"),newOb = {}
Els.forEach(each=>{
let key = each.getAttribute("data"), val = each.value
newOb[key] = val
})
return newOb
}
const main = document.querySelector(".root")
main.oninput = function(){console.log(getData(main))}
<div class="root">
<input class="border" data="col1" type="text">
<input class="border" data="col2" type="text">
<input class="border" data="col3" type="text">
<input class="border" data="col4" type="text">
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>