Skip to content

Looping Object properties in Ordered fashion

Last updated on January 23, 2020

Guys everyone of us atleast once in a while we’ve faced the situation of iterating Object properties in an ordered fashion.

Yes I also faced so I thought to share with you on this related to coding side.

To achieve this, usually we’ll end up using

for (item in user) { }

But using this way there is a downside. This pattern will iterate each properties of given object additionally object’s prototype also which happens under the hood. That’s not what we wanted to achieve.

To escape from this, we require an extra typing. What we going to use is for-loop pattern.

const User = {
  firstName : 'Srinivasan',
  lastName : 'K K',
  isLoggedIn: false
};

const propNames = [ 'firstName', 'lastName'];

for(let index =0,length=propNames.length; index <= length; index++) {
   
    // To access properties
      console.log(User[propNames[index]]);
}

One more tip would be, even we can use for-of pattern to loop through propNames array.

That’s it guys. I here share some day-to-day coding snippet which will accelerate and understand the technical things in much better way. Small things matters a lot, Grab it and help to create utilities that way we can help each other.

You can always comment, if you need help. I’ll try to help you out.

Published inJavaScriptReact