How do I retrieve the elements of an object after updating the application?

I have a form

<input type="text" id='name'>
<input type="text" id='place'>
<button id='add'>Add</button>        
<button id='show'>Show</button>

      

I have n object to collect items when add button is clicked and the code

var measure = {};
$("#add").click(function(){
    measurecol = new Object();
    measurecol.name = $("#name").val();
    measurecol.place = $("#place").val();
    measure[measurecol.name] = measurecol;
});

      

Whe I update my app, it first renders the elements of the object when there is no action in the Add button:

{ 'foo': { 'name':'foo', 'place': 'foo1' } }

      

But when I fill out the form and run the Add button, the old object element is removed and the new one is added to the object. This only happens when the app is updated.

So my question is how to restore the object element on application update and after adding the element it should add with the old one:

{
  'foo': {
    'name': 'foo',
    'place': 'foo1'
   },
   'goo': {
     'name': 'goo',
     'place': 'goo1'
   }
}

      

+3


source to share


4 answers


first you can check if the object is empty or not. If it is empty, add the element to the else object, if it is not empty, add the element depending on the length of the object.

if(measure != undefined && measure !={}){
    measure[measure.length] = measurecol;
}else{
    measure[measure.length+1] = measurecol;
}

      



hope this helps

+1


source


Whenever the click method is executed, you create a new object

measurecol = new Object();

      

which removes / replaces the previous object. Thus, you will lose your previously saved data.



if you don't use var in front of a variable name, it creates a global variable. This way you only have one variable measurecol that gets a new value each time.
add this

var measurecol = new Object();

      

0


source


use localStorage

var measure = localStorage;
$("#add").click(function(){ 
    measurecol.name = $("#name").val();
    measurecol.place = $("#place").val();
    measure[measurecol.name] = measurecol;
});

      

I think it will work

0


source


Usage localStorage

:

var measure = {};
$("#add").click(function(){
    measurecol = new Object();
    measurecol.name = $("#name").val();
    measurecol.place = $("#place").val();
    measure[measurecol.name] = measurecol;
    var lastobject =  localStorage.getItem("lastobj");

    if(lastobject){
        lastobject = JSON.parse(lastobject);
        var l = Object.keys(lastobject).length
        lastobject['obj'+l]=measurecol;
    }else{
        lastobject = new Object();
        lastobject.obj0 = measurecol;
    }
    localStorage.setItem("lastobj", JSON.stringify(lastobject));
});

      

0


source







All Articles