0

i have a function that loop all object properties and return value if it qualify certain condition

basically this is how i m doing

  //an enum    
 var BillingType = Object.freeze({
    PayMonthly: { key: 'Monthly', value: 1 },
    PayYearly: { key: 'Yearly', value: 2 }
});

now to make it work i do this

   for (var property in BillingType ) {
        if (BillingType .hasOwnProperty(property)) {
            if (value === BillingType [property].value) {
                return BillingType [property].key;
            }
        }
    }

it works fine but to make it generic for all enums i changed code to

getValue = function (value, object) {
    for (var property in object) {
        if (object.hasOwnProperty(property)) {
            if (value === object[property].value) {
                return object[property].key;
            }
        }
    }
}

now when i try to call from other functions

 enumService.getValue(1, 'BillingModel');

rather to loop all properties it start loop on its characters.

how can i convert string to object or m doing it totally wrong . any help will be appreciated

Regards

3
  • What you do with the two objects BillingModel and BillingType is strange. And why do you pass the name of the object instead of the object ? Did you want enumService.getValue(1, BillingModel);? Commented May 29, 2014 at 6:39
  • You want to pass the BillingType variable (your enum object), not the 'BillingModel' string?! Commented May 29, 2014 at 6:39
  • my mistake Guys . you all are right thanks for helping me Commented May 29, 2014 at 6:44

1 Answer 1

3

Your getValue looks fine, just call it using

enumService.getValue(1, BillingModel); // <-- no quotes

and here is a working fiddle: http://jsfiddle.net/LVc6G/

and here is the code of the fiddle:

var BillingType = Object.freeze({
    PayMonthly: { key: 'Monthly', value: 1 },
    PayYearly: { key: 'Yearly', value: 2 }
});

var getValue = function (value, object) {
    for (var property in object) {
        if (object.hasOwnProperty(property)) {
            if (value === object[property].value) {
                return object[property].key;
            }
        }
    }
};

alert(getValue(1, BillingType));
Sign up to request clarification or add additional context in comments.

2 Comments

You're welcome :) If my answer helped you feel free to upvote and/or accept it.
i just cant accept answer in 6 minutes :S SO restriction

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.