JAVASCRIPT
accessing nested objects in javascript
const user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: 'Jack',
address: {
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}
}
}
const name = user.personalInfo.name;
const userCity = user.personalInfo.address.city;
JavaScript Nested Objects
// nested object
const student = {
name: 'John',
age: 20,
marks: {
science: 70,
math: 75
}
}
// accessing property of student object
console.log(student.marks); // {science: 70, math: 75}
// accessing property of marks object
console.log(student.marks.science); // 70
js create nested object from fields
function assign(obj, keyPath, value) {
lastKeyIndex = keyPath.length-1;
for (var i = 0; i < lastKeyIndex; ++ i) {
key = keyPath[i];
if (!(key in obj)){
obj[key] = {}
}
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}
javascript nested objects
Do my eyes decieve me, or is the second answer the same as the first, but
with more upvotes?
js create nested object from fields
var settings = {};
assign(settings, ['Modules', 'Video', 'Plugin'], 'JWPlayer');
accessing nested objects in javascript
{key: value, key: value, ...}
nested object in javascript
const employeeInfo = {
employeeName: "John Doe",
employeeId: 27,
salary: {
2018-19: "400000INR",
2019-20: "500000INR",
2020-21: "650000INR"
},
address: {
locality: {
address1: "1600 pebble road",
address2: "Nearby XYZ Bank",
},
city: "Mumbai",
state: "Maharashtra",
country: "India"
}
}