You have two distinct types, which we can define typescript types for.
type FormatOne = {
desc: string;
number: string;
designation: string;
}
type FormatTwo = {
name: string;
ID: string;
role: string;
}
We can create a function to map from one type to the other.
const twoToOne = ({name, ID, role}: FormatTwo): FormatOne => ({
desc: name,
number: ID,
designation: role,
})
When parsing JSON from a string, you have to assert the type with as
because typescript does not know what the type will be. We can say that it will be an array with a mix of both types.
const str = '[{desc:"john",number:"22",designation:"manager"}, {name:"creek",ID:"198",role:"developer"}]';
const arr = JSON.parse(str) as Array<FormatOne | FormatTwo>;
If you know that you have an array of all FormatTwo
then reformatting it is as simple as calling array.map(twoToOne)
.
When you have a mixed array, we need to check each element and conditionally call the converter. We use 'name' in item
as a type guard to see if the item
is FormatTwo
.
const fixed = arr.map( item =>
('name' in item) ? twoToOne(item) : item
);
This new array fixed
has the type FormatOne[]
with no assertions required.