简体   繁体   中英

How to assign value to a property under an initialized parent property in javascript?

Say I have an object as below,

var ob = {}

Now I want to assign value to it as following

ob = {
  data: {
    id: '123456'
  }
}

I tried ob.data.id = '123456' , it prompts me that

TypeError: Cannot set property 'id' of undefined

Unless I make it this way

ob.data = {}
ob.data.id = '123456'

I'm wondering if there a easier/elegant way to achieve the same goal here? Much appreciated.

var ob = {};
ob.data.id = '123456';

The above code gives an error because, you have initialized the variable ob as an object but in the next line, you are trying to add a property id to ob.data . Here ob.data is not yet defined ( undefined ).

var ob = {};
ob.data = {};
ob.data.id = '123456';

This code works because, first you have initialized the variable ob as an object and then you have added a property data to it which is also an object and then finally adding the id property to the ob.data object.

As pointed out in the comment by @Lewis, you can combine the last two statements to a single statement as shown below.

var ob = {};
ob.data = {id: '123456'};

This would give the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM