Is it pointless to use hasOwnProperty
in the looping because object will always have properties?
For example:
const fruits = {
apple: 28,
orange: 17,
pear: 54,
}
for (let property in fruits) {
if (fruits.hasOwnProperty(property)) {
console.log(fruits[property]);
}
}
The better way to loop through objects is first to convert the object into an array. Then, you loop through the array. You can convert an object into an array with three methods: Object.
You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.
Use the Object. keys() method to get an array of the object's keys. Use the map() method to iterate over the array of keys.
If you're dealing with a plain object that doesn't inherit from another, such as with the code in your question, yes, the check will be unnecessary. When it'll be useful will be if you're iterating over an object which inherits from another. For example:
const fruit = {
isEdible: true
}
const apple = Object.create(fruit);
apple.color = 'green';
for (var property in apple) {
if (apple.hasOwnProperty(property)) {
console.log(apple[property]);
}
}
In this case the hasOwnProperty
check is needed to ensure the for..in
loop only console.log
s properties directly on the apple
object - otherwise, properties on the object apple
inherits from (that is, fruit
) will be printed as well:
const fruit = {
isEdible: true
}
const apple = Object.create(fruit);
apple.color = 'green';
for (var property in apple) {
console.log(apple[property]);
}
In the vast majority of cases, it's best to simply use Object.keys
(or Object.entries
or Object.values
) instead, which will iterate over properties directly on the object (ignoring inherited properties):
const fruit = {
isEdible: true
}
const apple = Object.create(fruit);
apple.color = 'green';
Object.values(apple).forEach((value) => {
console.log(value);
});
For your code, which is using a plain object literal that doesn't inherit from another (except for from Object
, which doesn't have any enumerable properties), it doesn't make a difference - but the functional Object methods are still generally nicer to work with than for..in
loops (which are forbidden by many linters)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With