I have a Typescript project in which I have an array of objects from which I want to extract the value of a key where another value matches the local variable.
I need to get the value of sheetId
of the object where the value of title
is equal to the value of fileName
This is my object:
JavaScript
x
21
21
1
let list = [
2
{
3
"properties": {
4
"sheetId": 1000297558,
5
"title": "ser"
6
}
7
},
8
{
9
"properties": {
10
"sheetId": 24134863,
11
"title": "atr"
12
}
13
},
14
{
15
"properties": {
16
"sheetId": 668935915,
17
"title": "work"
18
}
19
}
20
]
21
This is the variable:
JavaScript
1
2
1
let fileName = 'atr'
2
This is what I want to get:
JavaScript
1
2
1
let testId = 24134863
2
This is what I am doing, but I only get it to show me true in the object that matches, but I don’t know how to extract the key:
JavaScript
1
2
1
let sheetFile = list.map((elem: any) => elem.properties.title == fileName)
2
Update:
This is what I’m doing to find the value of sheetId:
JavaScript
1
2
1
let sheetId: number = list.find((elem: any) => elem.properties.title == fileName).properties.sheetId
2
This is the error it shows:
JavaScript
1
2
1
Error: Cannot read properties of undefined (reading 'properties')
2
My problem: how can I control that undefined or how can I assign it a 0, for example so that it has a value
Advertisement
Answer
You need to use .find
method to find and extract your value with dot notation.
JavaScript
1
25
25
1
const fileName = 'atr'
2
const list = [
3
{
4
"properties": {
5
"sheetId": 1000297558,
6
"title": "ser"
7
}
8
},
9
{
10
"properties": {
11
"sheetId": 24134863,
12
"title": "atr"
13
}
14
},
15
{
16
"properties": {
17
"sheetId": 668935915,
18
"title": "work"
19
}
20
}
21
]
22
23
const result = list.find((item) => item.properties.title === fileName).properties.sheetId;
24
25
console.log(result);