js create object in for loop code example

Example 1: javascript loop object

let obj = {
  key1: "value1",
  key2: "value2",
  key3: "value3"
}

Object.keys(obj).forEach(key => {
    console.log(key, obj[key]);
});
// key1 value1
// key2 value2
// key3 value3

// using for in - same output as above
for (let key in obj) {
  let value = obj[key];
  console.log(key, value);
}

Example 2: loop in object

const rgb = [255, 0, 0];

// Randomly change to showcase updates
setInterval(setContrast, 1000);

function setContrast() {
  // Randomly update colours
  rgb[0] = Math.round(Math.random() * 255);
  rgb[1] = Math.round(Math.random() * 255);
  rgb[2] = Math.round(Math.random() * 255);

  // http://www.w3.org/TR/AERT#color-contrast
  const brightness = Math.round(((parseInt(rgb[0]) * 299) +
                      (parseInt(rgb[1]) * 587) +
                      (parseInt(rgb[2]) * 114)) / 1000);
  const textColour = (brightness > 125) ? 'black' : 'white';
  const backgroundColour = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
  $('#bg').css('color', textColour); 
  $('#bg').css('background-color', backgroundColour);
}