Home > Back-end >  renaming keys / values in objects dynamically
renaming keys / values in objects dynamically

Time:06-03

I'm trying to put the values from the 'allValues' array inside the existing keys in the memory object, but instead they are just being added to the object after the existing keys, and they're keys are the index number. How can insert the values in the existing keys instead?

    const memories = {
        email: '',
        date: '',
        relation: '',
        tips: '',
        location: '',

    };

    const backend = (e) => {
        e.preventDefault();
        const allInputs = Array.from(document.querySelectorAll('input'));
        const allValues = allInputs.map(input => input.value);
      
        for (const [index, value] of allValues.entries(){
            memories[index] = value;
        }
        console.log(memories);
    };

CodePudding user response:

You're retrieving the input values as an array, so you don't have any information about the names of the form fields.

You probably want something like:

const allInputs = Array.from(document.querySelectorAll('input'));
const allValues = allInputs.map(({name, value}) => ({name, value}));
  
for (const {name, value} of allValues) {
    memories[name] = value;
}

Complete snippet:

const memories = {
    email: '',
    date: '',
    relation: '',
    tips: '',
    location: '',

};

const allInputs = Array.from(document.querySelectorAll('input'));
const allValues = allInputs.map(({name, value}) => ({name, value}));
  
for (const {name, value} of allValues) {
    memories[name] = value;
}

console.log(memories);
<input name="email" value="[email protected]">
<input name="location" value="World">

CodePudding user response:

See working example at CodeSandbox.

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Example</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <input type="text" name="email" value="a" />
    <input type="text" name="date" value="b" />
    <input type="text" name="relation" value="c" />
    <input type="text" name="tips" value="d" />
    <input type="text" name="location" value="e" />

    <button onclick="backend()">Submit</button>

    <script src="src/index.js"></script>
  </body>
</html>

index.js

const memories = {
  email: "",
  date: "",
  relation: "",
  tips: "",
  location: ""
};

window.backend = () => {
  const allInputs = Array.from(document.querySelectorAll("input"));

  allInputs.forEach((input) => {
    memories[input.name] = input.value;
  });

  console.log(memories);
};
  • Related