0

How can I add a property with a quoted name to an object (from outside of its declaration)?

Simplified Example:

var Obj = {}

Rather than:

Obj.dog = "Woof!";

I need to do:

Obj."dog" = "Woof!";

Similar to:

var Obj = {
    "dog" : "Woof!"
}

Except from outside of the declaration.

Real world scenario:

//Router, preload common files

var preloaded = {};

fs.readFile("index.html", function(err, data) {
    if (err) {
        throw err;
    }
    preloaded."/" = data;
});

Similar to:

//Preload common files
fs.readFile(index.html ", function (err, data) {
    if (err) {
        throw err;
    }
    var preloaded = {
        "/": data
    }
});

Then:

//Serve files, use preloaded data if it exists
http.createServer(function (req, res) {
    var reqObj = url.parse(req.url, true, true),
        pathName = reqObj.pathname;

    if (preloaded[pathName]) {
        res.writeHead(200);
        res.write(preloaded[pathName]);
        res.end();
    } else {
        // load and serve file or 404
    }
}).listen(8080);

Solved

In writing this question, I figured out my own answer. I'll post it as an answer, in case helpful. Perhaps someone else will have the same problem in the future.

WebDeveloper404
  • 1,215
  • 3
  • 10
  • 11

1 Answers1

0

The same way that you reference a quoted object property:

var Obj = {
    "dog" : "Woof!"
}

if (Obj["dog"]){ // true
   console.log(Obj["dog"]); // Woof!
}

You can also declare the property:

var Obj = {}
Obj["dog"] = "Woof!"

if (Obj["dog"]){ // true
   console.log(Obj["dog"]); // Woof!
}
WebDeveloper404
  • 1,215
  • 3
  • 10
  • 11