1

I'm creating a loop that takes a name and compares it to all the values in an array and stops and prints the name and number when it matches its value. Since the values are objects, I'm trying to convert the object to a string using toString() but it only returns [object Undefined] for me.

let name = 'Mustafa';
let i = 0;
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' },
]

i = 0
while (i < phonebook.length) {
  if (i === 4) {
  para.textContent = toString(phonebook[i]);
  } else {}

i++;
}

let section = document.querySelector('section');
section.appendChild(para);

2 Answers 2

1

You don't need a while loop for that, use Array.find

And use template literals to display the result or JSON.stringify the object :

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 obj = phonebook.find(e => e.name === name);

para.textContent = `name : ${obj.name} , number : ${obj.number}`;

// OR
// para.textContent = JSON.stringify(obj);

let section = document.querySelector("section");
section.appendChild(para);
<section></section>

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

Comments

0

By using JavaScript find method you can get the object that matches the name.

const contact = phonebook.find(item => item.name === name);

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.