Muhammad Haseeb Khan
Muhammad Haseeb Khan

Reputation: 895

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 create another object then how i can access obj like below code is not working with error Uncaught SyntaxError: Unexpected token [

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

What changes i need to made in io object to create detailObj

Upvotes: 0

Views: 83

Answers (4)

francadaval
francadaval

Reputation: 2481

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";

Upvotes: 0

Sebastien C.
Sebastien C.

Reputation: 4833

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";

Upvotes: 1

mechanicious
mechanicious

Reputation: 1616

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"]

Upvotes: 1

forgivenson
forgivenson

Reputation: 4445

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";

Upvotes: 0

Related Questions