Home > OS >  How to destructure an array/object
How to destructure an array/object

Time:03-13

I want to destructure this but i can't get it (I need the vcardArray)

I can't get it with .vcardArray or with const { vcardArray } = *variablename

[
    { 
        objectClassName: 'entity', 
        handle: '292', 
        roles: ['registrar'], 
        publicIds: [[Object]], 
        vcardArray: ['vcard', [Array]], 
        entities: [[Object]]
    }
]

CodePudding user response:

Destructuring syntax is exactly the same as object and array literal syntax,¹ it's just interpreted the other way around (and it's more common for us to use the shorthand {name} form than the full {name: name} form, though both are used).

So if you think about how you'd create an array with an object with a vcardArray property, that's how you destructure it.

const [ { vcardArray } ] = /*...your object...*/;

¹ With one caveat: The innermost tokens have to be assignable targets, so they can't be literals. {example: 42} is a valid object literal (creating an object with an example property and setting that property to 42), but you can't use it as a destructuring pattern because it would mean "get the example property and assign it to 42" you can't assign to the literal 42.

  • Related