Home > Net >  javascript: Cannot set properties of undefined
javascript: Cannot set properties of undefined

Time:08-25

I need to dynamically add a new property and try a couple of ways, but nothing works.

var streams = new Map();
streams.set(a, { id: 123 });
streams[a].context = some not-null object;

This is the error.

Cannot set properties of undefined (setting 'context')

So I try to pre-define context as an object.

var streams = new Map();
streams.set(a, { id: 123, context: {} });
streams[a].context = some not-null object;

But it still complains.

CodePudding user response:

var streams = new Map();
streams.set('a', { id: 123 });
streams.get('a').context = some not-null object;

You cannot get data like object/array from map. You have to use get to get the data

CodePudding user response:

Using the JavaScript Map class, you can get properties by using the get function. Here is an example:

var streams = new Map();
streams.set('a', { id: 123 });
streams.get('a').context = "";     // non-null object

You could also use an Object as so:

var streams = {
    a: {
        id: 123
    }
};

streams.a.context = "";
streams['a'].context = "";        // does the same thing
  • Related