Javascript object literal template: Extending implementation object with a baseline

I'm working with javascript object literals, and got the brilliant idea that I'd streamline the actual object literal I had to work with, by abstracting all the common attributes away.

As such I'd like to extend/inherit/merge my concrete object from a baseline predefined object structure. What I mean is something like this:

Baseline:

{  
       "id":"",
       "options":[  
          {  
             "1":true,
              "concreteValue":"important"
          },
          {  
             "2":false,
              "concreteValue":"unimportant"
          },
          {  
             "3":true,
             "concreteValue":"important"
          }
       ],
       "greeting":"Howdy",
       "player":{  
          "name":"",
          "hp":1,
          "mana":10
       }
}

Concrete:

{  
   "id":"player1",
   "options":[  
      {  
         "5":true,
          "concreteValue":"awesome"
      }
   ],
   "greeting":"Greetings!",
   "player":{  
      "name":"player1",
      "hp":15
   }
}

and through extending/inheriting/merging concrete with baseline, I want the output to be this:

{  
   "id":"player1",
   "options":[  
      {  
         "1":true,
         "concreteValue":"important"
      },
      {  
         "2":false,
         "concreteValue":"unimportant"
      },
      {  
         "3":true,
         "concreteValue":"important"
      },
      {  
         "5":true,
         "concreteValue":"awesome"
      }
   ],
   "greeting":"Greetings!",
   "player":{  
      "name":"player1",
      "hp":15,
      "mana":10
   }
}

So values that exist both places are overwritten by those in concrete, values that does not already exist are added. This seem like a good way of doing things, so I'm sure there's a smart way of doing this, that I haven't found yet :) I looked at jQuery Extend, but it doesn't seem to merge values by the same name into each other.

I tried using concat and Object.Assign, but they didn't do the trick either. Anyone got any ideas?

Answers 1

Related Articles