Skip to content Skip to sidebar Skip to footer

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 allUserExpir

Solution 1:

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;

Solution 2:

Using Computed property names from ES6, it is possible to do:

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

Solution 3:

Or you can do it:

functionsetByPath(obj, path, value) {
    var parts = path.split('.');
    var o = obj;
    if (parts.length > 1) {
      for (var i = 0; i < parts.length - 1; i++) {
          if (!o[parts[i]])
              o[parts[i]] = {};
          o = o[parts[i]];
      }
    }

    o[parts[parts.length - 1]] = value;
}

And use:

setByPath(obj, 'path.path2.path', someValue);

This approach has many weak places, but for fun... :)

Solution 4:

Why not just do this?

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

Solution 5:

I have a pretty hacky but short way of doing it in IE9+ as well as real browsers.

Given var path = 'aaa.bbb.ccc.ddd.eee'; where path is what your intending to make into an object and var result = {}; will will create the object {aaa: {bbb: {ccc: {ddd: {eee: {}}}}}

result = {}
path.split('.').reduce(function(prev, e) {
    var newObj = {};
    prev[e] = newObj;
    return newObj;
}, result);

will store the object in result.

How it works:

  • split('.') converts the input into ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
  • reduce(function (...) {...}, result) runs through the array created by split, and for each entry will pass along a returned value to the next one. In our case we pass the new object through after adding the new object to the old one. This creates a chain of objects. reduce returns the last object you return inside of it, so we have to defined result beforehand.

This relies on using references so it won't be immediately clear how it works if you're expecting your code to be maintained by anyone else and should probably be avoided to be honest, but it works at least.

Post a Comment for "Easy Way To Set Javascript Object Multilevel Property?"