I have various array data that looks like this:
Countries: [{code: "USA", countryDesc: "United States"},{code: "MEX", countryDesc: "Mexico"}]
and
States: [{code: "NY", countryDesc: "New York"},{code: "VA", stateDesc: "Virginia"}]
What I want to be able to do is convert the specific code/countryDesc or code/stateDesc to a "generic" key value pair to use. Hence, my conversion routine would provide me with this:
[{key:"USA", value:"United States"},{key:"MEX", value:"Mexico"}]
and
[{key:"NY", value:"New York"},{key:"VA", value:"Virginia"}]
My goal is to write a function that takes in the array and the names of the properties for the key and value and then converts them to an array with a key and a value instead of the other property names.
What I have is this:
export interface IAnyArray {
key: string;
value: string;
}
const convertToKeyValue = (
array: IAnyArray[],
keyname: string,
valuename: string
) => {
if (array && array.length > 0) {
return array.map((a) => {
return { key: a[keyname], value: array[valuename] };
});
}
};
I'm getting the error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IAnyArray'. No index signature with a parameter of type 'string' was found on type 'IAnyArray'.ts(7053)
for both a[keyname] and a[valuename] in the function.
This is how I would do it, specific to the input, but I'd like a "generic" mechanism if possible:
const convertCountriesToKeyValue = (
countries: { code: string; countryDesc: string }[]
) => {
return countries.map((country) => {
return { key: country.code, value: country.countryDesc };
});
};
I've searched the web and I'm unable to find anything useful to assist with this issue.
I'd appreciate any assistance in this. Thanks.