Nested objects inside an array


let spaceship = {
  passengers: [
      "Id and Name": {
        id1: {
          name: "Kirk",
          role: "Captain",
        id2: {
          name: "Spock",
          role: "Co-Captain",


console.log(spaceship.passengers["Id and Name"].id1);
// console.log(spaceship.passengers)

When I run the console above I receive:

TypeError: Cannot read properties of undefined (reading ‘id1’)

I’m not sure how to retrieve the key pair values?

when you work with an array of objects, you need to work with array methods like find().
You need to find a specific item of the array by its property like so:

const elmnt = spaceship.passengers.find(el => fn(el, 'Id and Name'));

Your callback function needs to crawl the keys of the object iterated and compare it to the key you are looking for:

const fn = (el, key) => Object.keys(el)[0] === key;

Then you can access the property id1:

console.log(elmnt['Id and Name'];

Since the 2nd argument for the callback function is hard coded, it would be smarter to use an object method for this task, so you can pass ‘Id and Name’ as an argument.