-1

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.

Clint_A
  • 518
  • 2
  • 11
  • 35

2 Answers2

1

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]);
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

Since you have used numbers as a property on the second object you must reference it differently than by name. use second[0] or second["0"]

var object = {
  key: function(n) {
    return this[ Object.keys(this)[n] ];
  }
};

function key(obj, idx) {
  return object.key.call(obj, idx);
}

var items ={'tv':390, 'table':200, 'cup':270, 'chair':325, 'door':300, 'books':290, 'radio':345};
var second ={0:30, 1:25, 2:20, 3:35, 4:30, 5:10, 6:15};
console.log(second["0"]);
console.log(items.tv/second[0]);
console.log(items.table/second["1"]);
// using helper

var myindex = 4;
console.log(key(items,4)/key(second,4));
 console.log("using helper")
   var count = Object.keys(items).length;
// so loop as long as they have same length
for (var i = 0; i < count; i++) {
  console.log(key(items,i)/key(second,i));
}

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100