1

I would like to iterate over the below and output a string that combines the different settings:

Loop through this:

config : {

   settings : {
     width: 880,
     height: 495,
     byline: false,
     title: false,
     portrait: false
    }
}

And output:

var output = '&height=495&width=880&title=false&byline=false&portrait=false',

How would I go about this?

0

3 Answers 3

6

I don't know whether you explicitly want to loop, but you can simply use jQuery.param:

var output = "&" + $.param(obj.config.settings);
// I assumed `obj` contains `config`

The order may be different but for a query string that does not matter.

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

7 Comments

Boo jQuery -- definitely not required! :)
@editor: If you have jQuery already on the page, then why not use it?
@editor: jQuery is never required, but the question was tagged as such so I figured it would be the easiest solution :) @ qwertymk: Thanks!
@user906080: qwertymk makes a good point. If you believe this is the best answer you should accept it as correct (and the same goes for any historical questions you've asked).
Somewhat new to the site. Apologize for my lack of adhering to the site guidelines. Will fix!
|
2
var attr, val, settings = config.settings,
    output, count = 0;
if ('undefined' !== typeof settings) {
    for (attr in settings) {
        val = settings[attr];
        if (0 === count) {
            output = output + val;
        } else {
            output = output + '&' + val;
        }
        count += 1;
    }
    console.log(output);
}

Note, the above code adds the optimization where you don't add an & to the first var. I don't think you'd want that in a get var string. If you do, just change to output = output + val; starting from if to end of else.

Comments

1

How about this:

function print( obj ) {
    return Object.keys( obj ).map( function ( name ) {
        return '&' + name + '=' + obj[ name ];
    }).join( '' );
}

Usage:

var output = print( obj.config.settings );

Live demo: http://jsfiddle.net/w3D9M/

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.