-2

I want to print the details in format: Key = Value,

However I get Undefined as the Valued.

var customers = [{
    'custID': 123,
    'name': "ABC"
  },
  {
    'custID': 456,
    'name': "DEF"
  }
]

for (x of customers) {
  for (key in x) {
    console.log(key + " = " + customers[key])
  }
}
adiga
  • 31,610
  • 8
  • 53
  • 74
Sumit
  • 41
  • 4

2 Answers2

1

use x instead of customers,

  • customers refers to original array and and coustomers[key] will be undefined as customers array donot have any key with name custId or name

var customers = [{'custID': 123,'name': "ABC"},{'custID': 456,'name': "DEF"}]

for (x of customers) {
  for (key in x) {
    console.log(key + " = " + x[key])
  }
}

Or you can simply use Object.entries

var customers = [{'custID': 123,'name': "ABC"}, {'custID': 456,'name': "DEF"}]


for (x of customers) {
  Object.entries(x).forEach(([key,value])=>{
    console.log(`${key} = ${value}`)
  })
}
Code Maniac
  • 35,187
  • 4
  • 31
  • 54
0

you must use x[key]

for (x of customers)
{
    for(key in x)
    {
        console.log(key + " = " + x[key])
    }
}
Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
ABlue
  • 632
  • 5
  • 19