skip to Main Content

code

Above is the code I have written to create an access a JSON array, however, when I run the console.log() command I get the following error:
enter image description here

2

Answers


  1. You have a json object that contains a field with key employees and value list of employees, to get the first employee you should access the list using the employees key, after accessing the value you can call the first item 0
    You should access employees first

    const my_json = 'myjson'
    const my_data = JSON.parse(my_json)
    const employees = my_data.employees 
    const myobj = employees[0].firstName
    
    Login or Signup to reply.
  2. In the code, you have a JSON string assigned to the employees variable, which you then parse into a JavaScript object. The JSON represents an object with a property employees which is an array of employee records.

    If the JSON is correctly parsed into the object myobj, and you want to access the firstName of the second employee (JavaScript is zero-indexed, so the second employee is at index 1), your code would look like this:

    console.log(myobj.employees[1].firstName);
    

    Make sure you access the employees array within the parsed object. If you attempt to access myobj[1], it will be undefined because myobj is not an array but an object with an employees property that is an array.

    If you are receiving an error, please check the following:

    1. Ensure the JSON string is valid.
    2. Ensure you’re accessing the correct property and index.

    If these are correct, the console.log() should output "Mary", which is the firstName of the second object in the employees array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search