0

I've got an object that declares other objects and then I'm looping through a series of inputs. Each of those inputs have a parent div that wraps them in sections so "credit, cash and debt".

var paymentObj = {
    credit: {},
    cash: {},
    debt: {}
};

$('.payments input').each(function(){
    var paymentCategory = $('input[class*="filter-section-"]').attr('class').match(/filter-section-(.*)/)[1];
    var paymentName = this.id;
}

If I do a console.log(paymentObj). I get values like:

Object { credit={visa=true, mastercard=false, amex=true}}, cash={}, debt={mastercard=true, amex=false}}

How would I get the values of just the credit object? I'm really looking to return if something is set to true in the credit object as comma delimited. visa, amex

I learn best by code samples so please include code samples. Any help is greatly appreciated!

2 Answers 2

1

You can use .map() on the paymentObj.credit object once the value is populated to get the comma delimited string

var credits = $.map(paymentObj.credit, function(a, b){
    return a ? b : undefined;
}).join(',')
console.log(credits)

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

Just so the non-jquery specific way is here:

var values = [];
for(var key in paymentObj.credit) {
    if(paymentObj.credit.hasOwnProperty(key)) {
        if(paymentObj.credit[key]) {
            values.push(key);
        }
    }
}

console.log(values.join(','));

Or depending on your browser support requirement, you may be able to drop the hasOwnProperty:

var values = [];
for(var key in paymentObj.credit) {
    if(paymentObj.credit[key]) {
        values.push(key);
    }
}

console.log(values.join(','));

Comments

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.