1

I might have two type of payloads.

const payload = {
   "firstName":"Steven",
   "lastName":"Smith"
}

or

const payload = {
   "personalDetails": {
       "firstName":"Steven",
       "lastName":"Smith"
    }
}

How can I retrieve firstName from the payload during a REST API call.

const { firstName } = payload;  

The above code will work for the first payload but it won't for the second payload since firstName is nested inside personalDetails. Is there a clean of retrieving it in ES6?

3 Answers 3

4
const { personalDetails: { firstName } } = payload;  

More about destructuring nested objects.

Sign up to request clarification or add additional context in comments.

1 Comment

Its debatable which one is cleaner, for me personally const { firstName } = payload.personalDetails seems more cleaner.
3

You cound take personalDetails property if not undefined or null or just the variable directly.

const { firstName } = payload.personalDetails ?? payload;

2 Comments

think ?? is more modern, does not support my codebase.
you could take logical OR || instead.
0

Strange scenario you have here but this might solve the issue:

const { firstName } = payload.personalDetails ? payload.personalDetails : payload;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.