Search code examples
javascriptlocal-storageform-data

Javascript: How to push key:pair values in Javascript Object which is already created


My question Explanation:

I have a variable of type = new FormData()

It has some key pair values for example.

    const _CheckOutData = new FormData(); // Creating FormData object to send mulitpart data
   _CheckOutData.append('Name', this._CheckOutForm.get('name').value);//Appending values to the 
   _CheckOutForm varibale from FormGroup
   _CheckOutData.append('Street', this._CheckOutForm.get('street').value);//Appending values to the 
   _CheckOutForm varibale from FormGroup
  _CheckOutData.append('City', this._CheckOutForm.get('city').value);/

I want to save these values in localStorages. when I directly save _ChechOutData to local storage its empty. Snippet of this function is

 SaveFormDataToLocalStorage(_CheckOutData){
     localStorage.setItem('_CheckOutData',JSON.stringify(_CheckOutData));
  }

So getting empty local Storage. I tried a different apporach which actually work but as my Question is I want to push the values from the _CheckOutData (Type FormData) into new object. here is the snippet

 _CheckOutData.forEach((key,value)=>{
       let Value=key;
       let Key=value;
       let TemporaryCart={
       [Key]:Value
     }
      this._CartCheckOutData.push(TemporaryCart);
   })

So I am Successfully getting all and values and save them into TemporaryCart (type Object). But the Problem is if there are 5 values it is created 5 object in the Array.But I want to creat one Object with 5 values in it.

My Actual Result:

 [{Name: "Fazi"}, {Street: "10570 S De Anza Blvd, Cupertino, CA 95014, United States"}]

But What I want

 [
     {
      Name:"Fazi",
      Street:"xyz 123",
      .
      .
      .
      .
      And So One
     }
 ]

Please Help me community: Regards Abdul Rehman


Solution

  • Hi you can try this one to change formdata in object

    formData.forEach(function(value, key){
        object[key] = value;
    });
    var json = JSON.stringify(object);