18th Jul 2010
Code
Comments (0)

I’ve been working a lot on my Superintendent project lately, and I just ran across an odd solution to a problem I was having. I’ve been writing the agent in Node.js, and I needed a way to get the output of /proc/meminfo into a clean, well-formatted JSON object. The issue I was having was I needed a way to assign object property names based on variables. Here’s what I mean:

var meminfo = new Object();
var someName = "objectPropertyName";

//now, assign an object property based on the variable
//someName's value
meminfo.someName = "some data here.";

You can probably already see the problem. The property that we assigned is called meminfo.someName, but we wanted it to be meminfo.objectPropertyName. How do we solve this? Well, first, let’s take a look at an associative array that would get the job done (albeit with an array):

var meminfo = new Array();
var someName = "arrayPropertyName";

//assign a value to the array with the key being the
//content of the variable 'someName'
meminfo[someName] = "some data here.";

That example would give us the variable meminfo['arrayPropertyName'] with the value some data here.. Exactly what we want, but with an object. So how do we do this? The answer is incredibly simple. Take the second example, but instead of creating a new array, create an object, and access it like an associative array:

var meminfo = new Object();
var someName = "objectPropertyName";

//assign a value to the array with the key being the
//content of the variable 'someName'
meminfo[someName] = "some data here.";

Now check and see of the object property exists; you’ll find that it does. We’ve successfully created a dynamic object property meminfo.objectPropertyName. All we had to do is access the object like an array.

Weird, but it works.

Comments
 
Please keep comments (fairly) clean.

Text can be formatted with Markdown. No HTML please.