Help: try to use loop

I use JavaScript code to search the name value out from the phonebook, and show the output including name and phone number as a paragraph nested inside element . I have tried the below codes, but seems it doesn’t work. Could somebody help me? Thank you.

 <body>

    <section class="preview">

    </section>

  
  <script>
    let name = 'Mustafa';
   
    let para = document.createElement('p');

    let phonebook = [
      { name : 'Chris', number : '1549' },
      { name : 'Li Kang', number : '9634' },
      { name : 'Anne', number : '9065' },
      { name : 'Francesca', number : '3001' },
      { name : 'Mustafa', number : '6888' },
      { name : 'Tina', number : '4312' },
      { name : 'Bert', number : '7780' },
      { name : 'Jada', number : '2282' },
    ]

    let i = 0;
    while(i<phonebook.length) {
    let seperate=phonebook[i].split(',');
    let seperate1=seperate[0].split(':');
    let seperate2=seperate[1].split(':');

    if (name===seperate1[1]){
    para.textContent= name + seperate2[1];
    break;
    } else { para.textContent = 'Contact not found.'}

   i++
    }
    
    let section = document.querySelector('section');
    section.appendChild(para);
  </script>
</body>

You don’t need to split objects. You can use their keys to access the data. So while you loop you can use

phonebook[i].name

phonebook[i].number

Good luck!

To expand on what @avidler said:

You cannot use the split method on an object. If you have a look at the documentation, you can see that is meant to work on Strings.

There are other methods for Objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#

1 Like