PaolaJ.
PaolaJ.

Reputation: 11532

Values from object like keys in dictionary doesn't work

I have created object in javascript like

function MetaEntity(){
this.energy = "energy";
this.name = "name";
}

var meta = new MetaEntity();

when I try to use values from meta like keys in dictionary it doesn't work.

var c = {meta.energy: 100,
         meta.name : "tekton"}

Can tell me what is a problem?

Upvotes: 0

Views: 51

Answers (4)

Luis Masuelli
Luis Masuelli

Reputation: 12333

function MetaEntity(){
    this.energy = "energy";
    this.name = "name";
}

var meta = new MetaEntity();

var c = {meta.energy: 100,
         meta.name : "tekton"}

will not work as you expect. will not try to produce {"energy": 100, "name": "tekton"} but {"meta.energy": 100, "meta.name": "tekton"}, which is not allowed in literal objects or will not produce the effect you want.

assign field by field: c = {}; c[meta.energy] = 100; c[meta.name] = "tekton";

Upvotes: 1

epascarello
epascarello

Reputation: 207501

You can not use variables when you are defining an object that way.

var c = {meta.energy: 100,
     meta.name : "tekton"
};

would need to be

var c = {};
c[meta.energy] = 100;
c[meta.name] = "tekton";

Other options is to extend the object.

Upvotes: 1

Steve H.
Steve H.

Reputation: 6947

You would need to use this syntax:

var c = {};
c[meta["energy"]]= 100;
c[meta["name"]]= "tekton";

Upvotes: 1

Kaarel Nummert
Kaarel Nummert

Reputation: 999

var c = {}
c[meta.energy] = 100;
c[meta.name] = "tekton";

Upvotes: 1

Related Questions