merry-go-round
merry-go-round

Reputation: 4625

Return the list of value of matching key from other object. (Intersection of two objects)

const validValuesByDataType: any = {
    [DataTypes.STRING]: [
        ValueType.CALL,
        ValueType.PUT,
    ],
    ...
}

const values: any = {
    [ ValueType.CALL ]: {value: 'call', label: 'CALL'}, 
    [ ValueType.PUT ]: {value: 'put', label: 'PUT'},
    ...
}

I would like to get the valid values based on the data type. Which is ['call', 'put']

const valueMap = validValuesByDataType[fieldType];
valueMap.map((o: any) => values[o].value); => I got "call" and "put" printing.

How do I get the array of value of values? I would like to have some kinds of form of something like this.

[ ...values.concat[type] ]

If you have any other better structure, any help will be highly appreciated.

Plus, I'm having trouble defining the type of each objects. Feel free to add any comments please!

Upvotes: 0

Views: 23

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42258

If you are using a new enough version of javascript then your value mapping is made easy by Array.prototype.flatMap.

function test(fieldType: DataTypes) {
    const valueMap = validValuesByDataType[fieldType];
    valueMap.flatMap(o => values[o].value);
}

ValueType and DataType seem to be enums, which can be used as a type. The typescript type Record describes an object where all of the keys are one type and all of the values are another type. That's what we'll use for the lookup objects.

const validValuesByDataType: Record<DataTypes, ValueType[]>

const values: Record<ValueType, {value: stringlabel: string;}>

TypeScript Playground Link

The enums are totally fine and there is no issue, but since you asked about other structures, the alternative would be to define your value types and data types as string literals.

Either of these have the same effect:

const valueTypes = ['CALL', 'PUT'] as const;

type ValueType = typeof valueTypes[number]; // evaluates to "CALL" | "PUT"

Link

type ValueType = "CALL" | "PUT";

const valueTypes: ValueType[] = ['CALL', 'PUT'];

Link

Upvotes: 1

Related Questions