简体   繁体   中英

Modify nested object and then return the modified parent object

I've got this function

function save(value, ...props)
{
    var record;
    var allRecords = JSON.parse(window.localStorage.getItem("data"));
    record = allRecords;
    for (var prop of props)
    {
        record = record[prop];
    }
    record = value;
    window.localStorage.setItem("data", JSON.stringify(allRecords));
}

whose job is to save a bunch of data in the window.localStorage. However, since JavaScript is a 'reference by value' language, modifying record doesn't affect the parent object ( allRecords ). So, how can I iterate throughout the storage object, modifying one its children, and then save the modified parent object?

You need to modify the parent object:

function save(value, ...props)
{
  var record = allRecords = JSON.parse(window.localStorage.getItem("data"));
  var parent=record;
  for (var prop of props)
  {
      parent=record;//store before modifying, so keep the parent
      record = record[prop];
  }

 parent[prop]= value;
 window.localStorage.setItem("data", JSON.stringify((allRecords));
 return parent;
}

However you now that your function goes "deep" into the object ( just saying):

save("hi","a","b","c");//will save like this
a={
   b={
     c="hi";
   }
}

Another possibility would be stop the loop right before the last iteration, then do record[prop]=value.

1.How objects are stored: Objects are stored by pointer. So in memory it looks like this (pseudocode):

//a memory location holding an object
432:
 val1:1
 val2:2

If you say the name of the object is a, a is stored like this:

a = location:432

if you copy it, for example with b=a, just the pointer is copied not the object:

a = location:432
b = location:432

If you change sth in the object a, it will in fact change the object at location 432, therefore b is changed to. Objects in Objects look the same:

//another obj
100:
   obj1:  location:432 //our pointer to the object

So our for loop (lets stay at the upper save example) will follow pointer to an object, get a property holding a pointer, than follow this pointer to another object ( a-> b -> c). These objects are stored somewhere in the mem. The JSON.stringify function does deep copy. So it follows every pointer and puts every necessary info into one string ( object ab and c).

  1. "Why does your code work and mys not?":

What you do

value=obj[key];
value="new";

What i do:

obj[key]="new";

But thats the same isnt it? NOPE. Lets look at the data in memory:

  //you
 //before
value:undefined
obj:
    key:"old"

//copying
value:"old"
obj:
     key:"old"

//changing

value:"new"
obj:
      key:"old" //never changed...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM