0

I have an array of objects that contains value pairs. I want to be able to access a value like this

myArray.code 
or
myArray[0].code

but it says myArray does not contain code. In the console this is what my array looks like. As you can see each object has two items in it and I want to access code and name by them selves not together and I dont know how to do this.

(2) [{…}, {…}]
0: {code: "PROG2700", name: "Client Side Programming"}
1: {code: "PROG1400", name: "jk"}
length: 2

this is the initial array holding these objects

 let [state_array_items, setState_array_items] = React.useState<Object[]>([]);
noobCoder
  • 181
  • 2
  • 11

1 Answers1

1

Your type of Object[] is took generic, so the Typescript compiler is throwing a fit. If you know that your type will always be { code: string; name: string }[], you should specify that and TS will be happy.

type SomeObject = { code: string; name: string };

let [state_array_items, setState_array_items] = React.useState<SomeObject[]>([]);

Here's a TS playground example of the TS compiler complaining when you just use Object[] but being okay when the type you provide is more specific:

Nick
  • 16,066
  • 3
  • 16
  • 32
  • 1
    Thanks for the reminder. I made an interface in my model that handled this so I can use it for other components, thanks – noobCoder Dec 15 '20 at 00:31