Abhishek Das
Abhishek Das

Reputation: 13

Usage of Object.keys() equivalent to for in loop?

How to use Object.key() for the below for in loop ?

for ( const obj in selectedObject) {
     objAdmin[ obj ] = this.adminData.find( function dataInEventType( eT ) {
            return eT[ 'Event Type' ] === newSelectedFilters[ obj ].LabelText;
        } );
     }

Upvotes: 0

Views: 281

Answers (3)

Patrick Barr
Patrick Barr

Reputation: 1123

Object.keys() returns a list of the enumerable keys in an object, it's pretty much the same as

var keys = [];
for(var prop in obj) {
    if(obj.hasOwnProperty(prop)) keys.push(prop);
}
return keys;

This means that you can just iterate over the list returned by Object.keys()

for(var i = 0; i < keys.length; i++) {
    // Do stuff with keys[i]
}

It's important to know that Object.keys() was defined in ES5 and legacy browsers like IE9 don't support this method, but the function I provided above could be used as a replacement if you would like to support older browsers.

It's also worth noting that there are differences between for and forEach... I tend prefer to use for to be able to break out of the loop if needed.

Upvotes: 1

ramesh sharma
ramesh sharma

Reputation: 254

Object.keys(selectedObject).forEach(function(obj){
objAdmin[ obj ] = this.adminData.find( function dataInEventType( eT ) {
            return eT[ 'Event Type' ] === newSelectedFilters[ obj ].LabelText;
        } );
}

Upvotes: 0

prasanth
prasanth

Reputation: 22500

Try like this forEach for iterate the array

Object.keys(selectedObject).forEach(function(a){
  objAdmin[ a ] = this.adminData.find( function dataInEventType( eT ) {
     return eT[ 'Event Type' ] === newSelectedFilters[ a ].LabelText;

})

Upvotes: 1

Related Questions