Another way would be like this.
somedata.forEach(item => {
div.innerHTML += "---" + item.lastname + "<br>";
});
The hasOwnProperty is new to me to. I don't know which is the best method.
WIth data like this:
[
{
"id": 122,
"lastname": "Ross"
},
{
"id": 123,
"lastname": "Smith"
},
{
"id": 124,
"lastname": "White"
}
]
For years I looped like this:
for (var i = 0; i < data['employee'].length; i++) {
var item = data['employee'][i];
div.innerHTML += "---" + item.lastname + "<br>";
}
But recently ran across the javascript hasOwnProperty(key) method. Or perhaps property.
So this also works:
for (var key in data['employee']) {
if (data['employee'].hasOwnProperty(key)) {
div.innerHTML += "---" + data['employee'][key].lastname + "<br>";
}
}
Both work. Which if either is the best, and do you have even a better way. Ignore the div.innerHTML part, just testing this out, real app I fill some fields with data.
I usually go for the forEach approach, unless I need to know which iteration I'm on.
Please or to participate in this conversation.