-1

Is there a way to use the for...in loop to iterate over the properties of two objects simultaneously? Assume for the sake of the argument that I need them to appear back to back in the console log (ie first property of element1 followed by first property of element2, the second property of element1, the second property of element2, and so on.....). This is a toy example that has no immediate practical application. I just want to understand the concept. If there is not a way to do this with the for...in loop is there a way to achieve the same effect assuming that I don't know anything about the number of properties that element1 and element2 have? The following code obviously will not work but captures the spirit of my intent (I hope...)

   function test(element1, element2) {
      for(var x in element1) {
         console.log(element1[x]);
         console.log(element2[x]);
      }
      return true;
    }

    element1 = {0:0, 1:1, 2:2};
    element2 = {a:0, b:1, c:2};
    test(element1, element2);
Shadow43375
  • 514
  • 7
  • 20
  • This is generally called "zipping". You zip the collections, the iterate over the zipped result. Although, your current way of using keys would already work, if you added the `hasOwnProperty` check. – Carcigenicate Feb 18 '18 at 01:19
  • See https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function – georg Feb 18 '18 at 01:21
  • Use Object.keys on both and iterate by index numbers simultaneously – Andrew Feb 18 '18 at 01:22

1 Answers1

0

Use the keys and check the length of both arrays.

function test(element1, element2) {
  var keys1 = Object.keys(element1),
      keys2 = Object.keys(element2),
      loop = 0;
      
  while(loop < keys1.length || loop < keys2.length) {
    if (loop < keys1.length) console.log(element1[keys1[loop]]);
    if (loop < keys2.length) console.log(element2[keys2[loop]]);
    
    loop++;
  }
  
  return true;
}

var element1 = {  '0': 0,  '1': 1,  '2': 2};
var element2 = {  a: 0,  b: 1,  c: 2,  d: 3,  z: 6};

test(element1, element2);
.as-console-wrapper {
  max-height: 100% !important
}
Ele
  • 33,468
  • 7
  • 37
  • 75