On click, loop through each object key

点点圈 提交于 2021-01-27 21:51:37

问题


I'm still learning JS and something is harder to understand than others.

Like so:

I am trying to change the theme of google maps by allowing users to click on a custom button.

I was using if else which works great but i wanted to add more themes and using a loop. Each time a user clicks, it selects:

object key 0, 
then click again object key 2 
and object key 3 
and repeat 

I can get the object keys and values how I'm lost after that.

  • This is the theme object

    let theme = { default: null, night: [multiple objects with nested arrays], dark: [multiple objects with nested arrays] }

  • creating button inside google maps then addEventListener

    let themeToggle = document.createElement('button'); themeToggle.classList.add('controlUI'); themeToggle.innerHTML = ('Mode'); themeToggle.title = 'Change map theme';

    map.controls[google.maps.ControlPosition.TOP_LEFT].push(themeToggle);

    let mode = true; themeToggle.addEventListener('click', () => { if (mode) { map.setOptions({styles: theme.night}); } else { map.setOptions({styles: theme.default}); } mode = !mode; });

Above Works Fine

Im struggling to convert the if else to a loop and select each object key and then adding that to:

map.setOptions({styles: theme.night})

and then on click it loops through each key and repeat

themeToggle.addEventListener('click', () => {
    for ( let key  in theme) {
      map.setOptions({styles: theme[key]});
      console.log(theme[key])
    }
  });

it selects the last one by default and i cant toggle.

Any help would e really appreciated, just trying add all the puzzle together.


回答1:


Collect the object values into an array, then increment an index with modulo on every click:

const vals = Object.values(theme);
let i = 0;
themeToggle.addEventListener('click', () => {
  map.setOptions({styles: vals[i]});
  i = (i + 1) % vals.length;
});

While most environments will result in an object's Object.values in ascending numeric followed by insertion order, it's not guaranteed. If you need a guaranteed predictable ordering, use Reflect.ownKeys (or Object.getOwnPropertyNames) instead:

const vals = Reflect.ownKeys(theme)
  .map(key => theme[key]);



回答2:


You can loop through an object like this

var invoice = {
  name: 'anik',
  age: 29,
  designation: 'Full Stack Developer'
}

Object.keys(invoice).map((d,i)=>{                 
  console.log(d +' : '+invoice[d]);
})


来源:https://stackoverflow.com/questions/57646374/on-click-loop-through-each-object-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!