简体   繁体   中英

Can I modify a local javascript object?

I have a stats object which is returned from firebase database

    var stats = await firebase
      .database()
      .ref("statistics")
      .child(currentUser.uid)
      .once("value");

The format of the object is like below:

stats  Object {
  "all": Object {
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
  "mtd": Object {
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
  "qtd": Object {
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
  "today": Object {
    "date": "Dec 7, 2019",
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
  "yesterday": Object {
    "date": "Dec 6, 2019",
    "pending": 0,
    "settled": 0,
    "vol": 0,
  },
  "ytd": Object {
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
}

Can I directly overwrite the stats.val().yesterday, say set the stats.val().yesterday to

    "date": "Dec 6, 2020",
    "pending": 1,
    "settled": 10,
    "vol": 1000,
  }

then use stats.val() with the latest changes? From what I did I still see old data before making changes to yesterday field. In this case, how can I get stats.val() with changes? Thanks!

val() returns a copy of the data in the snapshot, not the actual underlying object. If you modify this copy, it won't change what's stored in the snapshot. In this way, DataSnapshot is said to be "immutable" - it can't be changed. So, what you're trying to do is not possible.

Typically, app code is supposed to call val() just once to get a copy of the data, then use that copy to populate the UI.

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