0

I'm looking for something similar to the $set operator in Mongo and wasn't able to find it in the JS documentation:

http://docs.mongodb.org/manual/reference/operator/update/set/

I want to replace the value of a field to another specified value. If the field does not exist, I want to add the field with the specified value. BUT if there are existing fields in the object already I don't want to overwrite them.

Say that I've got this:

var hashTable = { key1: "Original Stuff", key2: "More Stuff" }

I want to update key2 to something else, but only key2. I want to leave key1 alone. Additonally, I want to add in a key3. It would be nice if there some something like:

var hashTable = hashTable.set( {key2: "Edited Stuff", key3: "Added stuff"} )

hashTable would then be

{ key1: "Original Stuff", key2: "Edited Stuff", key3: "Added Stuff" }

EDIT

Imagine that the original object and the object I want to use as an updating parameter both have tons and tons of fields. I'm not going to be doing hashTable.key2 = "Edited Stuff"

fuzzybabybunny
  • 5,146
  • 6
  • 32
  • 58

3 Answers3

1

So you're looking for the for..in statement, which lets you iterate over the keys of your object.

So in this case, you can easily write your function :

var setDict = function(target,extra){
    for(var property in extra){
         target[property]=extra[property];
    }
    return target;
}

Underscore.js also provides a function for this (_.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"}
Community
  • 1
  • 1
rtpg
  • 2,419
  • 1
  • 18
  • 31
  • Right. The object could have like 100 fields. There's no way I'm going to write explicit code for each field that checks on each of those 100 fields. Awesome... I didn't think to check in Underscore. I'll go try it right now. – fuzzybabybunny Jun 24 '14 at 09:39
  • WOOHOO `_.extend` was exactly what I was looking for! – fuzzybabybunny Jun 24 '14 at 09:47
  • Underscore has a lot of useful methods for general purpose operations in Javascript, always useful to flip through it to see if there's something that can fit your needs – rtpg Jun 25 '14 at 04:53
0

Simply do what you want:

var hashTable = { key1: "Original Stuff", key2: "More Stuff" }
hashTable.key2 = "Edited Stuff";
hashTable.key3 = "Added stuff";

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Rudy
  • 2,323
  • 1
  • 21
  • 23
0

To extend Rudy's answer (I was typing something similar!).

If you need to get the keys dynamically you can always use the object['property'] notation as well.

Dave
  • 145
  • 4