What is an Object in JavaScript/LWC:
An object is a list of name-value pairs of primitive data types. Each item in the list is called a property and each property name should be unique.
Here we are not going to explain more about the object. if your interested you can search in google to find more about javascript objects. Here we are going to show, how to create and access data of the Object in Lightning web components.
Creating Objects in LWC:
Almost same how we create object in apex. First we need to define an object and set properties values.
[Account acc = new account();acc.Name = 'Nagarjuna';acc.Phone = '1234567890';System.debug('Name: '+acc.Name);]
But in Javscript we can simply create an object defining properties inside of curly braces.
[import { LightningElement } from 'lwc';let account = {Name: 'Nagarjuna',Industry: 'crm',Phone: 1234567890};console.log(account.Name); // Nagarjunaexport default class App extends LightningElement {} ]
Accessing Properties in Object LWC:
Like we do access in Apex, using Object.Property name, same way we can also access in lwc.
[Account acc = [Select Id, Name, Phone from Account Limit 1];System.debug('Name'+acc.Name); // Nagarjuna]
We can access properties in an objects in two ways.
1. Dot Notation
[import { LightningElement } from 'lwc';let accountDetails = {isSelected: true,Account: {Name: 'Nagarjuna',Industry: 'crm',Phone: 1234567890}};console.log(accountDetails.isSelected); // trueconsole.log(JSON.stringify(accountDetails.Account)); // {"Name":"Nagarjuna","Industry":"crm","Phone":1234567890}console.log(accountDetails.Account.Name); // "Nagarjuna"export default class App extends LightningElement {}]
2. Bracket Notation
[import { LightningElement } from 'lwc';let accountDetails = {isSelected: true,Account: {Name: 'Nagarjuna',Industry: 'crm',Phone: 1234567890}};console.log(accountDetails['isSelected']); // trueconsole.log(JSON.stringify(accountDetails['Account'])); // {"Name":"Nagarjuna","Industry":"crm","Phone":1234567890}console.log(accountDetails['Account']['Name']); // "Nagarjuna"export default class App extends LightningElement {}]
COMMENTS