javascript - Any way to update a JS object but leave previous fields untouched? -
i'm looking similar $set
operator in mongo , wasn't able find in js documentation:
http://docs.mongodb.org/manual/reference/operator/update/set/
i want replace value of field specified value. if field not exist, want add together field specified value. if there existing fields in object don't want overwrite them.
say i've got this:
var hashtable = { key1: "original stuff", key2: "more stuff" }
i want update key2
else, key2
. want leave key1
alone. additonally, want add together in key3
. nice if there like:
var hashtable = hashtable.set( {key2: "edited stuff", key3: "added stuff"} )
hashtable
{ key1: "original stuff", key2: "edited stuff", key3: "added stuff" }
edit
imagine original object , object want utilize updating parameter both have tons , tons of fields. i'm not going doing hashtable.key2 = "edited stuff"
so you're looking for..in
statement, lets iterate on keys of object.
so in case, can write function :
var setdict = function(target,extra){ for(var property in extra){ target[property]=extra[property]; } homecoming target; }
underscore.js provides function (_.extend
).
usage :
var hashtable = { key1: "original stuff", key2: "more stuff" } hashtable = _.extend(hashtable,{key2: "edited stuff", key3: "added stuff"} ) // hashtable == {key1: "original stuff", key2: "edited stuff", key3: "added stuff"}
javascript
No comments:
Post a Comment