javascript access array of objects code example
Example 1: javascript array
var colors = ["red","blue","green"];
for (var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Example 2: javascript array read object value in array
var events = [
{
userId: 1,
place: "Wormholes Allow Information to Escape Black Holes",
name: "Check out this recent discovery about workholes",
date: "2020-06-26T17:58:57.776Z",
id: 1
},
{
userId: 1,
place: "Wormholes Allow Information to Escape Black Holes",
name: "Check out this recent discovery about workholes",
date: "2020-06-26T17:58:57.776Z",
id: 2
},
{
userId: 1,
place: "Wormholes Allow Information to Escape Black Holes",
name: "Check out this recent discovery about workholes",
date: "2020-06-26T17:58:57.776Z",
id: 3
}
];
console.log(events[0].place);
Example 3: javascript array of objects access properties
const user = {
id: 101,
email: '[email protected]',
personalInfo: {
name: 'Jack',
address: {
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}
}
}
const name = user.personalInfo.name;
const userCity = user.personalInfo.address.city;
const user = {
id: 101,
email: '[email protected]'
}
const name = user.personalInfo.name;
const name = user && user.personalInfo ? user.personalInfo.name : null;
let city;
if (
data && data.user && data.user.personalInfo &&
data.user.personalInfo.addressDetails &&
data.user.personalInfo.addressDetails.primaryAddress
) {
city = data.user.personalInfo.addressDetails.primaryAddress;
}