0

I have tried to search my problem but I couldn't even know how to ask it. I looked similar questions but I couldn't find anything. So here is my problem.

I have two js files. First one is constant.js which keeps HTTP field names. Here is the code snippet of it

module.exports = {
    USERNAME: 'username'
};

The second file is test.js and I would like to create some object inside of this file. While creating an object I would like to use constant.js file property names as shown in below:

var constant = require('./constant');

var x = {
    constant.USERNAME: "test"
};

console.log(x);

When i execute test.js I expected to see { username: 'test' } in the console but I got this following error:

constant.USERNAME: "test"
        ^
SyntaxError: Unexpected token .
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

I don't know why is it happening. Why can't I create my object? Any help would be greatly appreciated.

NOTE: Both files are on the same folder. There is no module export error. When I try to console.log(constant) it works well.

3 Answers 3

3

JS object literals (x = { ... }) consist of name: value pairs, where the name is a literal (and JS does not allow . in it), and you cannot use another variable here. To achieve what I think you want to achieve, I would do:

x = {};
x[constant.USERNAME] = "test";
Sign up to request clarification or add additional context in comments.

Comments

3

In case of literal object notation, the property names are not evaluated. Furthermore, constant.USERNAME is an invalid property name.

If you want to use the value of constant.USERNAME as the property name, you need to use the "array notation", like this:

var x = {};
x[constant.USERNAME] = 'test';

Comments

2

You should either use new syntax from ECMAScript 2015 (supported in nodejs 4 and newer):

var x = {
    [constant.USERNAME]: "test"
};

or stick with plain old:

var x = {};
x[constant.USERNAME] = "test";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.