简体   繁体   中英

JS Retrieve object from array and convert it to a string

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);

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>

通过使用 JavaScript find 方法,您可以获得与名称匹配的对象。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM