Link to home
Start Free TrialLog in
Avatar of JElster
JElsterFlag for United States of America

asked on

AngularJS - why doesn't this work - use object to store array values

Can you please tell me why this does not work.

HERE'S THE OBJECT


// Holds User selected fields & filter values
App.service('userFilters', function () {
    var store = {};

    this.toArray = function () {
        var records = [];
        return Object.keys(store).map(function (key) {
            records.push([key, store[key]]);
        });
    };

    this.get = function (key) {
        return store[key];
    };

    this.set = function (key, value) {
        store[key] = value;
    };
});


// HERE'S THE CODE TO USE IT

      userFilters.set('DD','XX');
         userFilters.set('a', 'b');
         userFilters.set('c', 'bdddddd');


// gET THE DATA

  var uFilters = userFilters.toArray();

            if (uFilters.length > 0) {
             

                for (p = 0; p < uFilters.length; p++) {

                    var x = uFilters[p];
                }
}
Avatar of Alexandre Simões
Alexandre Simões
Flag of Switzerland image

Ok mate, I still don't fully understand what you're trying to achieve mainly because the way your setting the values isn't compatible with the way you're accessing them.

Lets see, when you set the value you're passing a key and a value.
When you're accessing what are you trying to achieve?

The closest thing I can think here if to add a method in the factory that gives you all the items so that you can loop through them. Something like:
App.service('userFilters', function () {
    var store = {};

    this.get = function (key) {
        return store[key];
    };

    this.set = function (key, value) {
        store[key] = value;
    };

    this.getAll = function () {
        var result = [];

        for (var i in store) {
            var item = {};
            item[i] = store[i];
            result.push(item);
        }
        
        return store;
    };
});

Open in new window

This will give you a collection of objects that you can use in your loop as:
for (p = 0; p < userFilters.getAll().length; p++) {
    var x = userFilters[p];
}

Open in new window

But it's a mess because you don't know what's inside each object item...
That's why I don't understand what's your goal inside the loop.
Avatar of JElster

ASKER

I just trying to store an array of values.. thx again!

This doesn't seem to work.. does not loop

for (p = 0; p < userFilters.getAll().length; p++) {
    var x = userFilters[p];
}
ASKER CERTIFIED SOLUTION
Avatar of Alexandre Simões
Alexandre Simões
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial