In my Typescript project, I have an array of objects and I need to extract the value of a specific key based on a matching value in another key.
I want to retrieve the sheetId
value of the object where the title
matches the value of fileName
.
Here is the object structure:
let list = [
{
"properties": {
"sheetId": 1000297558,
"title": "ser"
}
},
{
"properties": {
"sheetId": 24134863,
"title": "atr"
}
},
{
"properties": {
"sheetId": 668935915,
"title": "work"
}
}
]
This is the variable:
let fileName = 'atr'
What I want to retrieve:
let testId = 24134863
I have tried using the map method to match the values, but I'm unable to extract the key:
let sheetFile = list.map((elem: any) => elem.properties.title == fileName)
Update:
To find the value of sheetId, I am using the find method:
let sheetId: number = list.find((elem: any) => elem.properties.title == fileName).properties.sheetId
However, I'm encountering an error:
Error: Cannot read properties of undefined (reading 'properties')
My issue: how can I handle the undefined value or assign it a default value like 0?