user2281858
user2281858

Reputation: 1997

javascript - find nested property from javascript object

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?

Upvotes: 1

Views: 38

Answers (3)

Eduardo Hernández
Eduardo Hernández

Reputation: 211

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

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

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

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

Upvotes: 3

James
James

Reputation: 22247

const { personalDetails: { firstName } } = payload;  

More about destructuring nested objects.

Upvotes: 4

Related Questions