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:
let list = [ { "properties": { "sheetId": 1000297558, "title": "ser" } }, { "properties": { "sheetId": 24134863, "title": "atr" } }, { "properties": { "sheetId": 668935915, "title": "work" } } ]
This is the variable:
let fileName = 'atr'
This is what I want to get:
let testId = 24134863
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:
let sheetFile = list.map((elem: any) => elem.properties.title == fileName)
Update:
This is what I’m doing to find the value of sheetId:
let sheetId: number = list.find((elem: any) => elem.properties.title == fileName).properties.sheetId
This is the error it shows:
Error: Cannot read properties of undefined (reading 'properties')
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.
const fileName = 'atr' const list = [ { "properties": { "sheetId": 1000297558, "title": "ser" } }, { "properties": { "sheetId": 24134863, "title": "atr" } }, { "properties": { "sheetId": 668935915, "title": "work" } } ] const result = list.find((item) => item.properties.title === fileName).properties.sheetId; console.log(result);