1

I'm building an object dynamically like this:

scope.filters[scope.col.field] = { value: scope.filterValue, operator: scope.filterOperator };

where scope.col.field is a string.

Then how do I loop through scope.filters in order to access value and operator for the various properties ?

Sam
  • 13,384
  • 25
  • 100
  • 178

2 Answers2

2

I think you are looking for the in operator, combined with the for loop. Check this MDN

or try like this:-

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

In your case:-

for (var fieldName in scope.filters) {
if (scope.filters.hasOwnProperty(fieldName))
{
 //.....
}
Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319
2

Here's a basic example:

for (var fieldName in scope.filters) {
    if (!scope.filters.hasOwnProperty(fieldName)) {
        alert(fieldName + ": " + scope.filters[fieldName]);
    }
}

for..in will go through all the members of an object.

It's a best practice to always check that the variable is its own member, so you don't pick up any other inherited functions or members. Here is a good explanation and example regarding why you should use hasOwnProperty.

I just set up an alert, but you can obviously do whatever you need with each fieldName and its value. Note, in this case, you'll get a lot of alerts.

Scott Mermelstein
  • 14,858
  • 4
  • 46
  • 75