xxxxxxxxxx
const {
address: { country },
} = user;
console.log(country);
// South Africa
xxxxxxxxxx
const obj = {a: {b: 'xyz'}};
const {a: {b}} = obj;
console.log(b); // xyz
xxxxxxxxxx
const person = {
name: 'labib',
age: 22,
job: 'web-developer',
frieds: ['ahsik', 'abir', 'alvi', 'hanafi'],
childList: {
firstChild: 'Salman',
secondChild: 'Rafi',
thirdChild: 'Anfi'
}
}
const { frieds: [a, b, c] } = person; //array destructuring from a nested object
console.log(a, b, c);
//expected output: ahsik abir alvi;
const { childList: { firstChild, secondChild } } = person; //object destructuring from a nested object
console.log(firstChild, secondChild)
//expected output:Salman Rafi
xxxxxxxxxx
const person = {
name: 'labib',
age: 22,
job: 'web-developer',
frieds: ['ahsik', 'abir', 'alvi', 'hanafi'],
childList: {
firstChild: 'Salman',
secondChild: 'Rafi',
thirdChild: 'Anfi'
}
}
//simple destructuring
const { name, age, job } = person;
console.log(name, age, job);
//Expected output: labib 22 web-developer
xxxxxxxxxx
const user = {
name: 'Chris',
age: 33,
username: 'DailyDevTips',
address: {
country: 'South Africa',
postalCode: '7700',
},
};
const {
address: { country },
} = user;
console.log(country);
// South Africa
xxxxxxxxxx
const {
address: { country },
} = user;
console.log(country);
// South Africa
xxxxxxxxxx
var personsInfo = {
company: 'sp-coder',
persons: [{
id: 1,
name: 'Adil',
friedsList: {
friend1: 'Nabil',
friend2: 'Habib'
}
}, {
id: 2,
name: 'Arif',
friedsList: {
friend1: 'alvi',
friend2: 'avi'
}
}]
};
const { friend1, friend2 } = personsInfo.persons[0].friedsList;
console.log(friend1, friend2);
// Expected Output: Nabil Habib
xxxxxxxxxx
const person = {
firstName: 'Adil',
lastName: 'Arif',
age: 25,
job: 'web-developer',
love: 'coding',
friedsList: {
friend1: 'Abir',
friend2: 'Adnan'
}
}
const { friend1, friend2 } = person.friedsList;
console.log(friend1, friend2);
//Expected output: Abir Adnan
xxxxxxxxxx
const user = {
name: 'Chris',
age: 33,
username: 'DailyDevTips',
address: {
country: 'South Africa',
postalCode: '7700',
},
};
const {
address: { country },
} = user;
console.log(country);
// South Africa
xxxxxxxxxx
const myFunc = ({event: {target: {name,secondName}}}) => {
console.log(name);
console.log(secondName);
}
myFunc({event: {target: {name: 'fred'}}})
xxxxxxxxxx
const item = {
id: 1234,
name: "sony wf1000xm3",
category: {
mainCategory: "electronics,
subCategory:'earphones'
}
};
const {
category: { subCategory },
} = item;
console.log(category);
// reference error
const {
category: { subCategory },
category,
} = item;
console.log(subcategory);
// earphones
console.log(category);
// {mainCategory: "electronics,subCategory:'earphones'}