Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to set javascript object multilevel property?

I am trying to create a javascript object like

var allUserExpiry={};
allUserExpiry[aData.userId][aData.courseId][aData.uscId] = aData;

But I am getting an error like allUserExpiry[aData.userId] undefined.

Is there a way, whereby I can set multi-level JS-Object keys? or is it important that I should go by doing allUserExpiry[aData.userId]={}, then allUserExpiry[aData.userId][aData.courseId]={} ?

Please let me know if there are any utility functions available for the same.

like image 246
linuxeasy Avatar asked Dec 06 '13 12:12

linuxeasy


People also ask

How do we assign object properties in JavaScript?

assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. Objects are assigned and copied by reference. It will return the target object.

Can you nest objects in JavaScript?

JavaScript can store data through key-value pairs. The key-value pairs are associated with the JavaScript objects. Objects contain properties that can be stored in nested objects. These nested objects are created within other objects and accessed through dot or bracket notation.

How do you assign object properties?

assign() Method: Among the Object constructor methods, there is a method Object. assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target.

How do you make a nested object in JavaScript?

const obj = { code: "AA", sub: { code: "BB", sub: { code: "CC", sub: { code: "DD", sub: { code: "EE", sub: {} } } } } }; Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple. We can solve this problem using a recursive approach.


1 Answers

No, there is no way to set "multilevel keys". You need to initialize each object before trying to add properties to it.

var allUserExpiry = {};
allUserExpiry[aData.userId] = {}
allUserExpiry[aData.userId][aData.courseId] = {}
allUserExpiry[aData.userId][aData.courseId][aData.uscId] = aData;
like image 171
meagar Avatar answered Oct 03 '22 04:10

meagar