0

i have an array of objects i need to append the 0 index object to a div and 1 index object to another div. Using switch case returns from the initial case itself not executing the second index

let arr = [{id:1,name:'test'},{id:2,name:'sample'}]
arr.forEach((obj,index) => {
  switch(index){
   case 0:
      $(".first p").text(obj.name)
   case 1:
      $(".second p").text(obj.name)
  }
})

after executing the first case it returns not executing the case 1?

Thanks in advance

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
Learner
  • 8,379
  • 7
  • 44
  • 82
  • 2
    Rolled back your edit. Don't update your question with the given answers, because both question and answers will become meaningless. – Robby Cornelissen Mar 07 '18 at 06:46
  • What output do you get and what it is the output you are expecting? – gurvinder372 Mar 07 '18 at 06:48
  • @RobbyCornelissen: i was upadting the question , the issue was not with the break statement, i just put the sample code . I was attaching an image to dom, the issue was with that one. Anyways thanks for the quick response – Learner Mar 07 '18 at 06:51
  • 1
    If the issue is with attaching image to DOM, then it is certainly not specified in your original question. Please share a working snippet demonstrating the issue you are having. – gurvinder372 Mar 07 '18 at 06:54
  • Well, you're providing sample code and besides the absence of the `break` statements there's no real issue with the code. Makes it hard for people to help. – Robby Cornelissen Mar 07 '18 at 06:54
  • Please add break; statement before each case – Dilip Oganiya Mar 07 '18 at 07:20

1 Answers1

1

You need to add a break statement to your cases, otherwise the execution will just "fall-through":

let arr = [{id:1, name:'test'}, {id:2, name:'sample'}];

arr.forEach((obj, index) => {
  switch(index) {
   case 0:
      $(".first p").text(obj.name);
      break;
   case 1:
      $(".second p").text(obj.name);
      break;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">
  <p/>
</div>
<div class="second">
  <p/>
</div>
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156