0

I get undefined when trying to access an object while iterating through an array.

obj={
"field":"value"
};

var arr=[values];

console.log(obj.entry);//works

arr.forEach(function(entry) {
console.log(entry); //works
console.log(obj.entry); //undefined
});
  • `console.log(obj.entry);` here it will give you undefined – Durga Jul 19 '17 at 05:21
  • how come `console.log(obj.entry);` works as there is no `entry` property? Seems you are looking for `console.log(obj[entry]);` – Satpal Jul 19 '17 at 05:21
  • I named it entry 'console.log(obj.entry);' just to show that the particular entry value from foreach exists in the object. Sorry if it was confusing. – Venkatesh Kandasamy Jul 19 '17 at 12:39

1 Answers1

-1

Use square brackets while accessing object key through a variable

obj = {
  "field": "value"
};

var arr = ["field", "field2", "field3"];
arr.forEach(function(entry) {
  console.log(obj[entry]); //value
});
brk
  • 48,835
  • 10
  • 56
  • 78