0

Very simple question here, I have the following variable. set up in a format like so {item number: quantity, item number, quantity....}

var x = {4214061251:1,2497227651:2,4214140739:2};

My question is simply how do i loop through this properly to access each element.

I would like to be able to access the item numbers and quantities separately, how can I achieve this?

chris cozzens
  • 517
  • 4
  • 19

1 Answers1

2

var x = {4214061251:1,2497227651:2,4214140739:2};

// Array of all keys 4214061251, 2497227651 ...
var keysArr = Object.keys(x);
console.log(keysArr);

// Iterate on keys
keysArr.forEach(
  (el) => {
    // To access keys
    console.log("Key: "+el);
    
    // To access values instead
    console.log("Value: "+x[el]);
  }
)
void
  • 36,090
  • 8
  • 62
  • 107
  • why such a complicated logic, you can directly use **for(var key in x){console.log(key, x[key]); }** – Rahul Sharma Feb 14 '18 at 17:08
  • @RahulSharma If you use for in to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods. – void Feb 14 '18 at 17:12
  • 1
    the results are not ordered? I didn't understand this because in JSON object you can't decide the order or keys. please help me to understand. – Rahul Sharma Feb 14 '18 at 17:18
  • `If you use for in to loop over property names in an object, the results are not ordered` They're not ordered when using `Object.keys` either. Admittedly they *usually* are, but there's absolutely no guarantees. Ordering is irrelevant to the OPs question, anyway. – Rory McCrossan Feb 14 '18 at 17:23
  • @RahulSharma This might be interesting for you then https://stackoverflow.com/a/23202095/1496715 – void Feb 14 '18 at 17:23
  • @RoryMcCrossan yea I agree.. I was quoting something why for ... in are not considered a solid approach to iterate over objects, until unless coupled with `.hasOwnProperty()` – void Feb 14 '18 at 17:24
  • this did work for what i was looking for, if there is a simpler way just let me know! – chris cozzens Feb 14 '18 at 17:28