0

I'm still a beginner in JavaScript and I need to create an object based on what the user types in the input fields.

Here are the input fields on my form:

enter image description here

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:

{
  // other data
  
  "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?

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
Tainara
  • 317
  • 1
  • 5
  • 14

2 Answers2

1

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

  // other data

  "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; }
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
0

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>
Amir Rahman
  • 1,076
  • 1
  • 6
  • 15