How useful are Built-in object methods?



How useful are Built-in object methods?


Let’s say we have an object that we want to make it into a drop-down menu. this will be a visual of what we have:

const objForMenu = {
  length: [100, 200, 300, 400],
  size: [20, 25, 30, 35, 40],
  weight: [110, 120, 130, 140, 150, 160, 170, 180, 190, 200],
  age: [18, 19, 20 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

so if we want to make a dropdown for keys and for values we could get the first ones with object.keys() and loop through them:
(we will be imagining that we already have the HTML unordered list on a variable list)

Object.keys(objForMenu).forEach(key => {
  let li = document.createElement('li');
  li.innerHTML = key;

and now, lets check for the second dropdown, let’s say we have a variable selected that stores the selection from the previous menu and we have another list already assigned to a secondList variable, we could use object.entries():

Object.entries(objForMenu).forEach((entry) => {
  if(selected === entry[0]){ 
//remember that .entries creates an array of arrays, so the first element of each inner array is the key
    entry[1].forEach(value => {
      let li = document.createElement('li');
      li.innerHTML = value;

So there we used .entries() to be able to have key and values in pairs, that made it easier for us to check if the selection from the first dropdown (saved in our selected variable) is the same as one of the keys, when we find the matching key, we grab the corresponding array value and loop though it to build our second dropdown.

there are many other useful ways for why you might want to use built-in object methods, but at least this will give you an idea for them.