Search code examples
javascriptarraysdestructuring

Destructuring Nested Arrays


If I have an array of objects that also has nested arrays, how do I get/destructure the sub array? For instance, what if I want to create a new array with only address object?

const people = [
  {
    name: "Jane",
    address: {
      street: "123 Main St",
      city: "Broadway"
    }
  },
  {
    name: "John",
    address: {
      street: "123 Other St",
      city: "Manhattan"
    }
  }
]

Solution

  • Please try this

    const people = [
      {
        name: "Jane",
        address: {
          street: "123 Main St",
          city: "Broadway"
        }
      },
      {
        name: "John",
        address: {
          street: "123 Other St",
          city: "Manhattan"
        }
      }
    ]
    
    const address=people.map((item)=>item.address)
    console.log(address);