javascriptjavascript-objectsmath-functions

How to perform a math function like divide on two js objects with different properties


Say I have a js object like this;

{'tv':390, 'table':200, 'cup':270, 'chair':325, 'door':300, 'books':290, 'radio':345}

and a second object like so;

{0:30, 1:25, 2:20, 3:35, 4:30, 5:10, 6:15}

How can I for instance perform a division on the first object by the second object per property key? That is {390/30, 200/25, 270/20, ... } The objects have the same number of properties.


Solution

  • The second should be an array.

    However I would not trust a for-in to stay in order - This does work though:

    var obj = {
      'tv': 390,
      'table': 200,
      'cup': 270,
      'chair': 325,
      'door': 300,
      'books': 290,
      'radio': 345
    }
    var divis = [30, 25, 20, 35, 30, 10, 15];
    var cnt = 0;
    for (var o in obj) {
      console.log(obj[o] / divis[cnt]);
      cnt++
    }
    
    // OR
    var keys = Object.keys(obj);
    for (var i = 0; i < keys.length; i++) {
      console.log(obj[keys[i]] / divis[i]);
    }