Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through object with hasOwnProperty check?

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]);
    } 
}
like image 455
I'll-Be-Back Avatar asked Dec 15 '18 23:12

I'll-Be-Back


People also ask

Can you loop through an object?

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.

How do I iterate through object keys?

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.

How do you loop through an object in react?

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.


1 Answers

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.logs 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)

like image 80
CertainPerformance Avatar answered Oct 17 '22 23:10

CertainPerformance