skip to Main Content

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?

2

Answers


  1. It’s not possible to access object properties dynamically using dot notation . However, with Bracket notation [], you can use a variable to dynamically access object properties.

    const myObj = [{
        "name": "harry",
        "id_1": "j-347",
        "id_2": "j-303"
      },
      {
        "name": "liouk",
        "id_1": "k-398",
        "id_2": "k-945"
      }
    ]
    
    function getId(counter, id) {
      console.log(counter);
      console.log(id)
      console.log(myObj[counter][id]);
      }
    getId(0, "id_1")
    Login or Signup to reply.
  2. 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, which is pointing to the required property

    function getId(counter, id) {
      console.log(counter);
      console.log(id)
      console.log(myObj[counter][id]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search