javascript - Switch statement to return result only when item type changes -
i have array of content when simplified looks this:
[ { content_type: 1, content_body: "some text" }, { content_type: 1, content_body: "some text" }, { content_type: 2, content_body: "media link" }, { content_type: 1, content_body: "some text" } ]
i need map through array , have switch statement checking content_type
, rendering html based on it, (note below syntax uses jsx, might different vanila javascript, pretty self explanatory).
switch(item.content_type) { case 1: render ( <div class="text_content"> <p>{item.content_body}</p> </div> ) case 2: render ( <div class="text_media"> <div>{item.content_body}</div> </div> ) }
now issue, if same content type follows 1 after in array (so first 2 entries content_type 1 example), want content_bodies rendered inside 1 div, so
<div class="text_content"> <p>{item.content_body}</p> <p>{item.content_body}</p> </div>
and continue on if next content_type different. (this can repeated several times in app, repeated content_type 1).
what approach this? bear in mind can't manipulate array things nest contents inside object.
if understood approach correctly should work fine. http://codepen.io/anon/pen/zrmejz - working example
code included below. logic on each iteration check if element exists new element inserted inside, if not, create element , add element inside. (note: jquery included library, can away using base js wanted show idea less code)
// sample array var arr = [ {content_type: 1, content_body: "some text"}, {content_type: 1, content_body: "some text"}, {content_type: 2, content_body: "media link"}, {content_type: 1, content_body: "some text"} ]; for(var = 0; < arr.length; i++) { var currentelement = arr[i]; console.log(currentelement.content_body); switch(currentelement.content_type) { case 1: var el = jquery('.text_content'); if(el.length) { el.append('<p>' + currentelement.content_body + '</p>'); } else { var el = jquery('<div class="text_content"></div>') el.append('<p>' + currentelement.content_body + '</p>'); jquery('body').append(el); } break; case 2: var el = jquery('.text_media'); if(el.length) { el.append('<div>' + currentelement.content_body + '</div>'); } else { var el = jquery('<div class="text_media"></div>'); el.append('<p>' + currentelement.content_body + '</p>'); jquery('body').append(el); } break; } }
.text_content { border: 1px solid black; } .text_content p { border: 1px solid yellowgreen; } .text_media { border: 1px solid blue; }
<html> <body> </body> </html>
i hope helps, let me know if requires tweaking. cheers.
Comments
Post a Comment