In a project which consume an API I receive a JSON payload as follow:
{
"data": {
"study": {
"id": "DEM1",
"locales": [
{
"locale": "en_IT",
"language": {
"direction": "ltr"
}
},
{
"locale": "en_US",
"language": {
"direction": "ltr"
}
}
]}
From this JSON I need to find with JS the locale en_US
and output the "direction": "ltr"
.
The locale is arriving inside a method where this JSON is get and I need to extract the right part of it which corresponding of the en_US
.
I got a difficulty how to do that in this situation
CodePudding user response:
Using Array#find
:
const obj = {
"data": {
"study": {
"id": "DEM1",
"locales": [
{
"locale": "en_IT",
"language": { "direction": "ltr" }
},
{
"locale": "en_US",
"language": { "direction": "ltr" }
}
]
}
}
};
const { language } =
obj?.data?.study?.locales?.find(({ locale }) => locale === "en_US") || {};
console.log(language);