Home > Net >  new Object with Key from Form on submit
new Object with Key from Form on submit

Time:11-07

I want that every time a form is submitted, a new equipment with the equipment number as KEY is created in the local storage.

E.g.

LocalStorage:

Key: Value:
E123456789 ordernumber: 456, date: 05.11.2022
E987654321 ordernumber :654, date: 05.11.2022

This is my code:

class Equipment {
  constructor(
    equipmentnumber,
    ordernumber,
    date
  ) {
    this.equipmentnumber = equipmentnumber;
    this.ordernumber = ordernumber;
    this.date = date;
  }
}

function addProcess() {
  let equipment = new Equipment(
    equipmentnumber.value,
    ordernumber.value,
    date.value
  );
  localStorage.setItem('equipment', JSON.stringify(equipment));
}

And this is what I get:

LocalStorage:

Key: Value:
Equipment equipmentnumber: 123, ordernumber: 456, date: 05.11.2022

CodePudding user response:

The first parameter of setItem is the key of the pair that you are trying to save. In your case you are passing equipment as a key so that explains your result. One of the following solutions might be what you are looking for.


Format the key using a template literal according to the example you gave us, ex. E123456789.

localStorage.setItem(`E${equipment.equipmentnumber}`, JSON.stringify({ordernumber: equipment.ordernumber, date: equipment.date}))

Or pass only the equipmentnumber as the key:

localStorage.setItem(equipment.equipmentnumber, JSON.stringify({ordernumber: equipment.ordernumber, date: equipment.date}))

CodePudding user response:

In addition to the already provided solution one could think about a class free (such an abstraction is really not needed) approach where one does both, creating the correct current equipment-data related storage-item which always is an object with e single key (the OP's equipmentnumber value from the OP's currently submitted form data) e.g. ...

{
  E123456789: {
    ordernumber: '456',
    date: '05.11.2022',
  }, 
}

... or ...

{
  E987654321: {
    ordernumber: '654',
    date: '05.11.2022',
  }, 
}

... and the correct merger of always the parsed current storage-data and the currently submitted equipment-data's related storage item.

For the above two equipment-data examples, where the first object is the currently stored data and the second object is the equipment-item equivalent of the just submitted form-data, the merger of the newly to be stored (updated) equipment-data would be ...

{
  E123456789: {
    ordernumber: '456',
    date: '05.11.2022',
  }, 
  E987654321: {
    ordernumber: '654',
    date: '05.11.2022',
  }, 
}

Thus, for a generic and/or more easy to maintain approach the OP needs to

  • firstly create a FormData instance of the currently processed/submitted form ...

    const formData = new FormData(evt.currentTarget);
    
  • ... since in a second step it is easier to create/reduce an object from all of the formData.entries().

    const itemData = [...formData.entries()]
      .reduce((result, [key, value]) =>
        Object.assign(result, { [ key ]: value }), {}
      );
    
  • The related current (and to be merged/stored) equipment-data object then most easily is created by an immediately invoked arrow function expression which allows for the most generic equipmentnumber specific object creation by using the rest parameter syntax in combination with the spread syntax

    const currentEquipmentData = (({ equipmentnumber, ...data }) => ({
      [ equipmentnumber ]: { ... data }
    }))(itemData);
    
  • The parsed currently stored equipment-data ...

    const storedEquipmentData = JSON
      .parse(
        localStorage.getItem('equipment-data') ?? null
      ) ?? {};
    
  • ... then has to be merged (e.g. again by spread syntax) before ...

    const mergedEquipmentData = {
      ...storedEquipmentData,
      ...currentEquipmentData,
    };
    
  • ... the such updated equipment-data is going to be stored again ...

    localStorage.setItem(
      'equipment-data',
      JSON.stringify(mergedEquipmentData),
    );
    

function handleEquipmentItemStorage(evt) {
  evt.preventDefault();

  const formData = new FormData(evt.currentTarget);

  const itemData = [...formData.entries()]
    .reduce((result, [key, value]) =>
      Object.assign(result, { [ key ]: value }), {}
    );

  const currentEquipmentData = (({ equipmentnumber, ...data }) => ({
    [ equipmentnumber ]: { ... data }
  }))(itemData);

  const storedEquipmentData = JSON
    .parse(
      mock.localStorage.getItem('equipment-data') ?? null
    ) ?? {};

  const mergedEquipmentData = {
    ...storedEquipmentData,
    ...currentEquipmentData,
  };
  // delete an empty key.
  Reflect.deleteProperty(mergedEquipmentData, '');

  if (Object.keys(mergedEquipmentData).length >= 1) {

    mock.localStorage.setItem(
      'equipment-data',
      JSON.stringify(mergedEquipmentData),
    );
  }

  console.log({
    itemData,

    currentEquipmentData:
      structuredClone?.(currentEquipmentData) || currentEquipmentData,

    storedEquipmentData:
      structuredClone?.(storedEquipmentData) || storedEquipmentData,

    mergedEquipmentData:
      structuredClone?.(mergedEquipmentData) || mergedEquipmentData,
  });

  return false;
}

function main() {
  document
    .querySelector('form')
    .addEventListener('submit', handleEquipmentItemStorage);
}
main();
body { margin: 0; }
form { width: 28%; }
form input { display: block; width: 100%; margin: 4px 0; }
form button { margin: 8px 0; }
.as-console-wrapper {
  left: auto!important;
  max-height: unset!important;
  height: 100%;
  width: 69%;
}
<script>
  // mock for the SO specific stack snippet
  // due to the policies and environment are
  // not allowing an original storage access.
  const mock = {
    localStorage: (function () {

      // https://developer.mozilla.org/en-US/docs/Web/API/Storage
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
      const storage = new Map;

      function key(int) {
        return [
          ...storage.keys()
        ][parseInt(int, 10)];
      }

      function setItem(key, value) {
        return storage.set(String(key), String(value));
      }
      function getItem(key) {
        return storage.get(String(key));
      }

      function removeItem(key) {
        return storage.delete(String(key));
      }

      function clear() {
        return storage.clear();
      }

      return {
        get length() {
          return storage.size;
        },
        key,
        getItem,
        setItem,
        removeItem,
        clear,      
      };

    }()),
  }
</script>

<form action="/" method="post">
  <input type="text" name="equipmentnumber" placeholder="equipment number" />
  <input type="number" name="ordernumber" min="400" max="600" step="1" placeholder="order number" />
  <input type="date" name="date"/>

  <button type="submit">submit equipment item</button>
</form>

<button onclick="console.clear()">clear console</button>

  • Related