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 ?

1
  • 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 Commented Sep 4, 2015 at 16:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

updated, I declared dict to be an Array<string> initially, which is quite improper considering the overall intention here...

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.