-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
  • 34,372
  • 9
  • 61
  • 83
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
  • 37,143
  • 5
  • 39
  • 60
0

you must use x[key]

for (x of customers)
{
    for(key in x)
    {
        console.log(key + " = " + x[key])
    }
}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
ABlue
  • 664
  • 6
  • 20