1

I am trying to add a key dynamically to an obj but I keep getting error "Can not set property of undefined" But I cant decalre these properties before knowing them. I want them to added dynamically as a key to that object.

var dict = {}
 objectarray.forEach((item: Obj) => {
        this.dict[item.ID] = "xyz";
    });

As per How do I add a property to a Javascript Object using a variable as the name? it seems possible to add property to object dynamically just by using obj[name] = value.

Am I missing something ? Any help ?

Community
  • 1
  • 1
Govind Kalyankar
  • 574
  • 1
  • 4
  • 17
  • The problem is not that you can't set a property like that, the problem is that you are trying to set a property of "undefined". this.dict is not defined – Matt R Sep 04 '15 at 16:50

2 Answers2

4

Remove the this in this.dict and you should be golden!

var dict = {}
objectarray.forEach((item: Obj) => {
   dict[item.ID] = "xyz";
});

Without seeing more of the code it's hard to say what this means in this context, but most likely it's the window object, so what you're saying is basically window.dict[item.ID] = "xyz". Since there's no dict property on the window it'll blow up like that.

Oskar Eriksson
  • 2,591
  • 18
  • 32
0

@Oskar's answer is correct.

Here is a more verbose code sample;

enum memberTypes
{
    None,
    Property,
    Method
}

class memberInfo {
    memberName: string;
    memberType: memberTypes;
    constructor(name: string, mtype: memberTypes)
    {
        this.memberName = name;
        this.memberType = mtype;
    }   
    toString() {
        return JSON.stringify(this);
    }
}

class propertyInfo extends memberInfo
{
    constructor(name: string) 
    {       
        super(name, memberTypes.Property);
    }   
}

class methodInfo extends memberInfo
{
    constructor(name: string) 
    {       
        super(name, memberTypes.Method);
    }   
}

var dict = new Object();
var objectArray = new Array<memberInfo>();

objectArray.push(new propertyInfo("Name"), new methodInfo("toString"));

objectArray.forEach((item) => { 
    if (item.memberType === memberTypes.Property)
    {
        if (item.memberName === "Name") {
            dict[item.memberName] = 'SysName';
        }       
    } else if (item.memberType === memberTypes.Method) {

        if (item.memberName === "toString") {
            dict[item.memberName] = function() { return JSON.stringify(this); };
        }
    }   
    console.log(item.toString());
})

console.log(dict);

TypeScript Playground Example

Brett Caswell
  • 732
  • 1
  • 4
  • 16
  • updated, I declared `dict` to be an `Array` initially, which is quite improper considering the overall intention here... – Brett Caswell Sep 04 '15 at 17:27