0

How to loop string in each object add to one string like below result?
I need to add each variable this_encode to one string, how to do it?

result: '<img src=""><iframe></iframe><img src="">'

for (var key in obj) {
    if (obj[key].file_type == 0) {
        var this_encode = '<img src="' + obj[key].file_name + obj[key].file_format + '">';
    } else if(obj[key].file_type == 1) {
        var this_encode = '<iframe width="150" height="100" src="'+obj[key].file_embed_url +'" frameborder="0" allowfullscreen></iframe>';
    }
}

obj

file_embed_url: ""  
file_format: "jpg"  
file_name: "53b21c90dded9"  
file_sequence: "0"  
file_type: "0"  
gallery_id: "1"  
id: "138"  

file_embed_url: "//www.youtube.com/embed/-x6jzKpqeuw"  
file_format: ""  
file_name: ""  
file_sequence: "1"  
file_type: "1"  
gallery_id: "1"  
id: "139"  

...
5
  • What is the data for obj? Commented Jul 1, 2014 at 2:45
  • 2
    declare your string outside the loop and then use concatenation to create a single string. Commented Jul 1, 2014 at 2:45
  • @jasonscript thanks for reply, can you make a example? Commented Jul 1, 2014 at 2:47
  • @AdamMerrifield obj is javascript object like above example Commented Jul 1, 2014 at 2:49
  • @user1775888 declare this_encode before you start the for. So it would be var this_encode = ''; then for (var key in obj) {. Inside the for just replace var this_encode = with this_encode += . Commented Jul 1, 2014 at 2:52

1 Answer 1

3

Declare your this_encode variable outside the loop and then use concatenation to create a single string

// first initialise your variable as an empty string; can't concatenate to undefined
var this_encode = '';

// Now run your code as before with 2 small differences
//      (1) Remove the var declarations
//      (2) Use += instead of = to indicate that you want to append the following text to the this_encode variable
for (var key in obj) {
    if (obj[key].file_type == 0) {
        this_encode += '<img src="' + obj[key].file_name + obj[key].file_format + '">';
    //  ^           ^ see the change here
    //  |
    //  var declartion removed from here (and below)
    } else if(obj[key].file_type == 1) {
        this_encode += '<iframe width="150" height="100" src="'+obj[key].file_embed_url +'" frameborder="0" allowfullscreen></iframe>';
        //          ^ and here
    }
}
Sign up to request clarification or add additional context in comments.

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.