Carl Edwards
Carl Edwards

Reputation: 14434

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?

Upvotes: 1

Views: 2191

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

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)

Upvotes: 6

f278f1b2
f278f1b2

Reputation: 311

If you need the name of first object you should write

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

console.log(name);

Upvotes: 1

Related Questions