I am currently attempting to loop through a JSON array using TypeScript.
To help with comprehension, I have created a simple example involving a person interface.
However, I am encountering an issue with the line:
isArray(curr[k]) ? curr.[k]?.[0] : curr[k],.
ERROR: Identifier expected
Here is the code snippet in question:
import { isArray } from 'lodash';
const myObj = {
"allData" :{
"person" : [
{
"name":"John",
"age":30,
"email":"djsbjb"
},
{
"name":"rohit.sharma.my.name",
"age":20,
"email":"fdbfhdbfn"
}
]
}
};
interface Person {
name: String,
age: number,
email?: String
}
const example = (
person: Person
) => {
//rohit,sharma,my,name"
const k = myObj.allData.person[1].name.split(
'.'
) as (keyof typeof person)[];
console.log(`output of k: ${k}`);
const curr = { ...person};
console.log(`output of curr: ${curr}`);
if (!curr) {
return;
}
const ans = k.map((k) =>
isArray(curr[k]) ? curr.[k]?.[0] : curr[k],
);
return ans;
}