0

After reading this SO post I am still having issues looping over my data structure:

users:
 {
   'names': ['john','chris'],
   'addresses': ['10 king street', '20 king street'],
 }

The loop:

for (const prop in this.payload) {
      console.log(prop); //names

      for (const item of prop) {
           console.log(item); //n //a //m //e //s
      }
 }

It appears to be outputting the letters of the key "names", then doing the same for the other keys.

Why? The expected output is:

names
john
chris
addresses
10 king street
20 king street
panthro
  • 22,779
  • 66
  • 183
  • 324

2 Answers2

1

prop is a string. If you loop over a string, you will loop over its characters, and that is what you're seeing.

Instead, obtain the value referred to by that property name, and loop over that value:

this.payload = {
  'names': ['john', 'chris'],
  'addresses': ['10 king street', '20 king street'],
};

for (const prop in this.payload) {
  console.log(prop); //names

  for (const item of this.payload[prop]) {
    console.log(item);
  }
}

Better yet, make use of Object.entries():

this.payload =  {
   'names': ['john','chris'],
   'addresses': ['10 king street', '20 king street'],
};

for (const [prop, items] of Object.entries(this.payload)) {
    console.log(prop);
    
    for (const item of items) {
        console.log(item);
    }
}

Or you could use Object.values() if you don't care about the property names.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Thanks. With object.values I get "items is not iterable" – panthro Jan 28 '18 at 18:30
  • @panthro With `Object.values` you would need to change the first `for` to `for (const values of Object.values(this.payload))` – JLRishe Jan 28 '18 at 18:31
  • Thanks, why use values over entries? And why use these over for loops? – panthro Jan 28 '18 at 18:32
  • @panthro _" Thanks, why use values over entries?"_ Use `.values` if you only care about the values and not the property names ("names", "addresses"). Use `.entries` if you want the values and the property names. _"And why use these over for loops?"_ These are `for` loops. – JLRishe Jan 28 '18 at 18:34
0

To access the values, use this.payload[prop]

for (const prop in this.payload) {
  console.log(prop); //names

  for (const item of this.payload[prop]) {
       console.log(item);
  }
 }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51