简体   繁体   中英

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?

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)

If you need the name of first object you should write

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

console.log(name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM