1

I have two arrays with the following structure:

First dictionary:

 [{id: 111, abbr: "FBI", name: "Federal Burreau of Investigation"},
 {id: 59, abbr: "CIA", name: "Central Intelligence Agency"},
 {id: 130, abbr: "EU", name: "European Union"}]

Second dictionary:

 [{id: 28, name: "Administration"},
 {id: 107, name: "Advocacy"},
 {id: 100, name: "Agriculture"},
 {id: 77, name: "Air & Aviation"}]

I am trying to create a delimiter function that accesses these objects in the following way:

 finalDictionary.push({ delimiter: dictionary[0].abbr.charAt(0) });

and correspondingly:

 finalDictionary.push({ delimiter: dictionary[i].name.charAt(0) });

My aim is to make the method universal and diminish the amount of final code. As you see, the only difference here is the property by which I am accessing the dictionary, 'abbr' and 'name'. I tried to do it the following way:

 var ext = (name === 'agencies') ? 'abbr' : 'name';
 finalDictionary.push({ delimiter: dictionary[i].ext.charAt(0) });

However, I get an error:

 TypeError: Cannot read property 'charAt' of undefined

The question is how can I conditionally access the object property? Maybe, there is a better approach than this one? If not, what am I doing wrong?

Eugene
  • 37
  • 5

2 Answers2

4

The problem is in this line:

dictionary[i].ext.charAt(0)

dictionary[i].ext assume that you have a property ext inside dictionary[i] which you don't and therefore it returns undefined.

than what happens is undefined.charAt(0) which raises your error

Change it to:

dictionary[i][ext].charAt(0)

Than the property here is the value of ext which is 'abbr' or 'name'

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
  • 1
    Thank you, this is it! I should have used bracket notation to access the property via string which I get as a result of my ternary. Appreciated :) – Eugene Nov 15 '18 at 12:17
  • This is a matter of 2 more minutes :) – Eugene Nov 15 '18 at 12:20
0

There is no property named ext in the example json you have shown, that is why you are facing this error.

codeLover
  • 2,571
  • 1
  • 11
  • 27
  • Ext is a variable storing the name of the property to be used, I am getting it via a ternary – Eugene Nov 15 '18 at 12:19