Skip to content Skip to sidebar Skip to footer

Creating Javascript Object From Simple Object

Suppose i have this object var io={'NAME':'Battery For Alarm Panel','CODE':'POWER MAX','OWN':'ONM'} which i can access like below io['NAME'] or io['CODE'] etc. But if want to cr

Solution 1:

The object["property"] syntax is meant to access an object properties and doesn't have anything to do with the syntax for object creation. If you want to access an object several levels down, follow the example below:

var basket = {
    box: { 
          mobilePhone: "mobilePhone"
         }
}

To access mobilePhone property of basket you would use: basket.box.mobilePhone or basket["box"]["mobilePhone"]

Solution 2:

You can't use JSON syntax with a dynamic key.

You have many solutions :

var detailObj = {};
detailObj[io.NAME] = {};
detailObj[io.NAME][io.CODE] = {};
detailObj[io.NAME][io.CODE][io.OWN] = "12";

or

var detailObj = {};
var detailObjNAME = (detailObj[io.NAME] = {});
var detailObjCODE = (detailObjName[io.CODE] = {});
detailObjCODE[io.OWN] = "12";

or

var detailObj = {};
((detailObj[io.NAME] = {})[io.CODE] = {})[io.OWN] = "12";

Solution 3:

You can't declare an object like that, using variables inside of the object declaration for the property names. You'll have to create the object like this:

detailObj = {};
detailObj[io['NAME']] = {};
detailObj[io['NAME']][io['CODE']] = {};
detailObj[io['NAME']][io['CODE']][io['OWN']] = "12";

Solution 4:

var io={"NAME":"Battery For Alarm Panel","CODE":"POWER MAX","OWN":"ONM"};

var detailObj = {};
detailObj[io['NAME']] = {};
detailObj[io['NAME']][io['CODE']] = {};
detailObj[io['NAME']][io['CODE']][io['OWN']] = "12";

Post a Comment for "Creating Javascript Object From Simple Object"