r/JavaScriptTips • u/OlanValesco • Jun 24 '19
Use Object.entries() to loop through the the keys and values in an object
This is from ES2017
const users = {
'c1g6hhsus': {name: 'Matthias Broue', dob: '1990-05-04'},
'uhwtpyce2': {name: 'Jenette Vix', dob: '1998-12-01'},
'nvt89pzgx': {name: 'Osman Tragger', dob: '1989-12-26'},
'9gcvl8lbj': {name: 'Tamara Islington', dob: '1993-09-18'},
};
const statements = Object.entries(users).map(([key, val]) => `<li>${val.name}'s user ID is ${key}.</li>`);
document.querySelector('.idStatements').innerHTML = `<ul>${statements.join('')}</ul>`;If you wanted, you could also deconstruct val to just get name out:
const statements = Object.entries(users).map(([key, {name}]) => `<li>${name}'s user ID is ${key}.</li>`);
8
Upvotes
1
u/[deleted] Jun 24 '19
I'd like to point out that using
.innerHTML()is against best practices and a serious security risk. In the example you provide, it would be better to insert the<ul>...</ul>into whatever.querySelector('.idStatements')returns via the use of.appendChild().https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
In fact, I'd do the same for adding the
<li>...</li>elements to the<ul>...</ul>as opposed to building out a string.