0

Here's my code:

headersObj = {a: "a", b: "b", c: "c"};
headers = ["a", "b", "c"];
fields = ["a", "b"];

notInTemplate = [];

headers.forEach(function(obj) {
  if(fields.indexOf(obj) == '-1'){

    console.log(headersObj.c);
    console.log(headersObj.obj);
    console.log(obj);
    notInTemplate.push(obj);
  }
});
console.log(notInTemplate);

I could explain more about my use case, but I just want to be able to "headersObj" property, so I can push it to the "notInTemplate" array. I've distilled it to this fairly simple example. The output of which is:

c undefined c [ 'c' ]

Why is the object property undefined?

James Bowler
  • 2,194
  • 2
  • 17
  • 23
  • 2
    You want `headersObj[obj]` instead of `headersObj.obj`. The latter looks for a property named exactly `obj`, and you did not have one. You only have `a`, `b`, and `c`. – Ray Toal May 11 '18 at 01:24

1 Answers1

-1

You have to use bracket notation ([]) to access the object's property dynamically:

headersObj = {a: "a", b: "b", c: "c"};
headers = ["a", "b", "c"];
fields = ["a", "b"];

notInTemplate = [];

headers.forEach(function(obj) {
  if(fields.indexOf(obj) == '-1'){

    console.log(headersObj.c);
    console.log(headersObj[obj]);
    console.log(obj);
    notInTemplate.push(obj);
  }
});
console.log(notInTemplate);
Mamun
  • 66,969
  • 9
  • 47
  • 59