I’m getting the following data returned from an API:
{
"statusCode": 200,
"successful": true,
"userPreferences": [
{
"category": "Alerts",
"preference": {
"ContentViolations": "true",
"UserCommentsYou": "true",
"UserMessagesYou": "true"
}
},
{
"category": "Display",
"preference": {
"DateFormat": "mm-dd-yyyy",
"TimeFormat": "12-hour"
}
},
{
"category": "EmailList",
"preference": {
"ReceiveDailyDigest": "true",
"ReceiveDealsOffers": "true"
}
},
{
"category": "Privacy",
"preference": {
"OtherUsersMessageYou": "true",
"OtherUsersViewProfile": "true"
}
},
{
"category": "Units",
"preference": {
"Measurement": "inches",
"Weight": "pounds"
}
}
]
}
I need to extract a preference
value from a key value pair. Here is what I have:
const result = userPreferences?.filter(x => x.category === "Alerts" && x.preference["UserMessagesYou"]).map(x => x.preference.value);
It’s returning string[] | undefined
but I would like it to retutn string
.
In the example above I would like result
to have the value "true".
3
Answers
The way I see it, I assume you want to extract one
UserMessagesYou
value fromuserPreferences
array which has categoryAlerts
right? If so, this should do it:The prop preference does not have a props named value ,so it’s undefined
it returns undefined because the property value does not exist within the preference object.
(It’s in the last operation that you do within the map function: .map(x => x.preference.value))
According to your validation, the properties you have available are:
Then you can do something like this:
Property UserMessagesYou is accessed on the map:
I hope this answer has helped you.