0

I have an object like this:

const myObj = [
{
 "name": "harry",
 "id_1": "j-347",
 "id_2": "j-303"
}, 
{
 "name": "liouk",
 "id_1": "k-398",
 "id_2": "k-945"
}
]

If I want to access hary's id_1 (or id_2) I have to type

myObj[0].id_1 (or id_2)

I have this function:

function getId(counter, id) {
 console.log(counter);
 console.log(id)
 console.log(myObj[counter].id;
}

but when I call getId(0, "id_1") I get:

0
id_1
undefined

In addition, if I delete the line "console.log(id)" from the function, my code editor tells me that 'id' is declared but its value is never read, despite the fact that I use it on the last line of the function.
It seems like the argument "id_1" not be recognized after the . (console.log(myObj[counter].id;)

What do I do wrong?

user3513782
  • 43
  • 1
  • 8

1 Answers1

0

the function you have written needs a little tweak, as id property doesnt exist inside the array u have provided instead u are passing it as string, and it to be placed inside square bracket

function getId(counter, id) {
  console.log(counter);
  console.log(id)
  console.log(myObj[counter][id]);
}
Nithin P.H
  • 671
  • 1
  • 9
  • 29