0

Basically I have a json say.. collectionData = {'customerName':'Ashish','phone':'1234567'} Now I have an array containing json fieldnames like..

array = ['customerName','phone'];

Now I want to perform this operation :

for (let i = 0; i < array.length; i++) {
    console.log(collectionData.array[i]);
}

Why this code is giving me error? Thanks is advance

Ele
  • 33,468
  • 7
  • 37
  • 75
Ashish Maity
  • 35
  • 1
  • 9

1 Answers1

1

You'll have to access them using bracket notation. Coz when you do that using . dot notation what happens is

console.log(collectionData.array[0])  // undefined - 
//it looks for .array[0] property which gives you undefined

That's why it is advised to use bracket notation in such cases

Now consider the following

  console.log(collectionData[array[0]])

This will first resolve array[0] to customerName and will give you value if exists.

If you still want to access using dot notation there is still a way to do that. Something like

var collectionData = {'customerName':'Ashish','phone':'1234567'}
var array = ['customerName','phone'];
for(var i=0; i<array.length; i++)
console.log(eval('collectionData.'+array[i]))
Muhammad Usman
  • 10,039
  • 22
  • 39