简体   繁体   中英

How to create complex object structure in javascript?

I'm trying to create a structure of object using classes in javascript. I have a problem creating objects which involve nested structure. For example ..

{
    "id" : 1,
    "name" : "mark",
    "phoneNumber" : "123456789",
    "dob" : "2010-08-20",
    "address" : {
        "latitude" : 123214.1231,
        "longitude" : 1231243.12,
        "houseNumber" : "1-2-3",
        "landmark" : "square-garden",
        "pinCode" : "134567876"
    }
}

I think this way works, Instead of using class just use functions:

function AddressDto(latitude, longitude, houseNumber, landmark, pinCode) {
    this.latitude = latitude || 0;
    this.longitude = longitude || 0;
    this.houseNumber = houseNumber || '';
    this.landmark = landmark || '';
    this.pinCode = pinCode || '';
}
    
function UserCreationDto(id, name,phoneNumber, dob, address) {
    this.id = id || 0;
    this.name = name || '';
    this.phoneNumber = phoneNumber || '';
    this.dob = dob  || '';
    this.address = address || new AddressDto();
}

const user = new UserCreationDto();
user.id = 1;
user.name = 'test';
user.phoneNumber = '1234567890';
user.dob = '12/12/12';
console.log(user.address.latitude);

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