I’m new to typescript and would like to extract the value from JSON objects inside an array with changing property names.
My (simplified) code is as follows:
const data = [
{ names: { "1,2": "Matthew" },
{ names: { "2,3": "Marcus", "3,4": "Bill" }},
{ names: { "4,5": "Joana", "5,6": "Bob" }
];
const key = "1,2";
const name = data[0].names[key]; // Results in an error message (see below)
const name = data[0].names["1,2"]; // Works but not dynamic
My goal is to extract each value (e.g. “Matthew”, “Marcus”, etc.).
However, I get the following error message:
Type ‘{ names: { “1,2”: string; “2,3”?: undefined; “3,4”?: undefined; “4,5”?: undefined; “5,6”?: undefined; }; }’ is not assignable to type ‘string’
How can I solve this error?
Thanks a lot for your help!