Skip to content Skip to sidebar Skip to footer

Javascript: Loop Through Object Properties

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. The

Solution 1:

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.


Solution 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))
{
 //.....
}

Post a Comment for "Javascript: Loop Through Object Properties"