JackLiebling
JackLiebling

Reputation: 11

Is there a way to destructure a property that has no name from an object?

The response I am getting from a fetch() is

{errors: {"": [,…]}, type: "https://tools.ietf.org/html/rfc7231#section-6.5.1",…}

errors: {"": [,…]}
   "": [,…]
      0: "Error converting value \"field.value\" to type 'System.Collections.Generic.List`1[System.String]'. Path '', line 1, position 13."
status: 400
title: "One or more validation errors occurred."
traceId: "00-fc1fd022e2c5545a24909a8c7a15c38d-f930263d77c54f34-00"
type: "https://tools.ietf.org/html/rfc7231#section-6.5.1"

I am able to destructure errors, status, title, traceId, and type from the object, but since the destructured errors is another object, with a nameless array inside it, I am not sure how to destructure it further to access the array.

Upvotes: 1

Views: 68

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187184

You can destructure that, but you need to provide a valid identifier for it.

const res = { errors: { "": ['an error'] } }

const { errors: { "": messages }} = res

console.log(messages) // ['an error']

See playground


That said, I don't think this is very readable code. It's pretty confusing what's happening here. I think its is probably far more clear to do something like:

const messages = res.errors['']

Lastly, providing data on a property named empty string, is pretty strange. That also seems like a bad idea since it generates confusion like this whole question.

Upvotes: 1

Related Questions