Search code examples
javascriptecmascript-6destructuring

Destructuring nested objects in an array


I basically want to pull out the first object within an array and get it's name. The only challenge here is that I'm trying to destructure this within a parent object:

const exampleObject = {
  collection: [{
    name: "First Object",
  }, {
    name: "Second Object",
  }],
};

const {
  collection: [firstObject: {
    name
  }]
} = exampleObject;

console.log(firstObject);

Is sort of thing possible?


Solution

  • You need to switch it to:

    {name: firstObject}
      |        |________ New variable name
      |    
      |_________________ Property name
    

    const exampleObject = {collection: [{name: "First Object",}, {name: "Second Object",}],}
    
    const { collection: [{ name: firstObject }] } = exampleObject
    
    console.log(firstObject)