In order to check from my frontend application if there is or not a PDF I want to search into my nested object ‘translations’ for the field named “pdf_url”.
JavaScript
x
55
55
1
{
2
"id": 118,
3
"name": "MIXY",
4
"thumbnail": null,
5
"translations": [
6
{
7
"field": "name",
8
"lang": "it",
9
"text": "MIXY"
10
},
11
{
12
"field": "name",
13
"lang": "en",
14
"text": "MIXY"
15
},
16
{
17
"field": "thumbnail",
18
"lang": "en",
19
"text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypng.png"
20
},
21
{
22
"field": "pdf_url",
23
"lang": "en",
24
"text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypdf.pdf"
25
}
26
]
27
},
28
{
29
"id": 119,
30
"name": "CITY",
31
"thumbnail": null,
32
"translations": [
33
{
34
"field": "pdf_url",
35
"lang": "en",
36
"text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypdf.pdf"
37
},
38
{
39
"field": "name",
40
"lang": "it",
41
"text": "CITY"
42
},
43
{
44
"field": "thumbnail",
45
"lang": "en",
46
"text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypng.png"
47
},
48
49
{
50
"field": "name",
51
"lang": "en",
52
"text": "CITY"
53
},
54
55
The problem I am dealing with i that for every cardObject (id: 118, 119) the pdf_url can be in position 0, 1, 2, 3 or n inside that the translations array. So when I try to access it like this, for example
JavaScript
1
2
1
cardObject?.['translations']?.[2]?.['text']
2
I am not always sure I check the “pdf_url” of my card. I would firstly check is the object has “pdf_url” key value using
JavaScript
1
2
1
card?.['translations'].hasOwnProperty('pdf_url')
2
and then? Should I loop over the translations array of objects? Is there a simple way to “reduce” or even better group my data?
Advertisement
Answer
You can use Array.prototype.find
to find the first object in the array that has a field
property with the value pdf_url
.
JavaScript
1
4
1
const pdfUrl = cardObject.translations.find(translation => translation.field === 'pdf_url');
2
console.log(pdfUrl.text);
3
// /var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypdf.pdf
4