lodash#uniq TypeScript Examples
The following examples show how to use
lodash#uniq.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: list.monad.ts From relate with GNU General Public License v3.0 | 6 votes |
unique(predicate?: (val: T) => any) {
if (predicate) {
// @ts-ignore
return this.map((val) => uniqBy(val, predicate));
}
// @ts-ignore
return this.map(uniq);
}
Example #2
Source File: number-set.ts From dyngoose with ISC License | 6 votes |
toDynamo(values: Value): DynamoDB.AttributeValue {
if (!isArray(values) || !every(values, isNumber)) {
throw new ValidationError(`Expected ${this.propertyName} to be an array of numbers`)
}
// dynamodb does not allow sets to contain duplicate values, so ensure uniqueness here
return {
NS: uniq(values.map((value) => numberToString(value))),
}
}
Example #3
Source File: addresses.ts From nautilus-wallet with MIT License | 6 votes |
function extractAddressesFromInput(input: UnsignedInput): string[] {
if (input.ergoTree.startsWith(P2PK_TREE_PREFIX)) {
return [addressFromErgoTree(input.ergoTree)];
}
let pks = extractPksFromP2SErgoTree(input.ergoTree);
if (input.additionalRegisters) {
pks = pks.concat(extractPksFromRegisters(input.additionalRegisters));
}
if (isEmpty(pks)) {
return [];
}
const addresses: string[] = [];
for (const pk of uniq(pks)) {
addresses.push(addressFromPk(pk));
}
return addresses;
}
Example #4
Source File: schemaEditor.ts From next-basics with GNU General Public License v3.0 | 6 votes |
export function processFormData(
data: SchemaItemProperty
): SchemaRootNodeProperty {
const result: SchemaItemProperty = omit(data, ["fields", "import"]);
const requiredList: string[] = [];
const defaultData: Record<string, unknown> = {};
const importSet = new Set<string>();
result.fields = [];
if (data.required) {
requiredList.push(data.name);
}
if (!isNil(data.default)) {
defaultData[data.name] = data.default;
}
collectImport(data, importSet);
collectFields(
data.fields,
{ requiredList, defaultData, importSet },
result.fields
);
return {
...result,
required: uniq(requiredList),
default: defaultData,
...(importSet.size !== 0 ? { import: Array.from(importSet) } : {}),
};
}
Example #5
Source File: scanProcessorsInStoryboard.ts From next-core with GNU General Public License v3.0 | 6 votes |
export function scanProcessorsInAny(data: unknown, isUniq = true): string[] {
const collection: string[] = [];
visitStoryboardExpressions(
data,
beforeVisitProcessorsFactory(collection),
PROCESSORS
);
return isUniq ? uniq(collection) : collection;
}
Example #6
Source File: bar-chart.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
CP_BarChart = (props: CP_BAR_CHART.Props) => {
const { cId, data, props: configProps, extraContent, operations, execOperation } = props;
const { yAxisLabelLen, title, tip, visible = true, chartStyle, ...rest } = configProps || {};
const { option } = data || {};
const { color, ...optionRest } = option || {};
const presetColor = map(newColorMap);
const reColor = color ? uniq(map(color, (cItem) => newColorMap[cItem] || cItem).concat(presetColor)) : presetColor;
if (!visible) return null;
const onEvents = {
click: (params: any) => {
const dataOp = get(params, 'data.operations.click') || operations?.click;
if (dataOp) {
execOperation(dataOp, {
data: params.data,
seriesIndex: params.seriesIndex,
dataIndex: params.dataIndex,
});
}
},
};
const { option: reOption, isEmpty } = getOption({ color: reColor, ...optionRest }, configProps);
const ChartComp = <EChart key={cId} onEvents={onEvents} option={reOption} notMerge {...rest} style={chartStyle} />;
return (
<div className={`cp-bar-chart ${getClass(configProps)}`}>{isEmpty ? <EmptyHolder relative /> : ChartComp}</div>
);
}
Example #7
Source File: hooks.ts From gant-design with MIT License | 6 votes |
garidShowSelectedRows = (selectedRows, apiRef: any, getRowNodeId, isSingle: boolean) => {
const gridSelectedRows = apiRef.current.getSelectedRows();
const gridSelcetedKeys = gridSelectedRows.map((item = {}) => getRowNodeId(item));
const selectedKeys: string[] = selectedRows.map((item = {}) => getRowNodeId(item));
if (selectedKeys.length === 0) apiRef.current.deselectAll();
const allKeys = uniq([...gridSelcetedKeys, ...selectedKeys]);
if (isSingle) {
const [key] = selectedKeys;
const singleNode = apiRef.current.getRowNode(key);
singleNode && singleNode.setSelected(true, true);
return;
}
allKeys.map(id => {
const nodeItem = apiRef.current.getRowNode(id);
if (!nodeItem) return;
if (selectedKeys.indexOf(id) >= 0) nodeItem.setSelected(true);
else nodeItem.setSelected(false);
});
}
Example #8
Source File: TranslationMap.ts From mo360-ftk with MIT License | 6 votes |
public static convert(map: ITranslationMap): ITranslation[] {
const languages: string[] = keys(map);
let translationIds: string[] = [];
const translations: ITranslation[] = [];
forEach(languages, language => {
translationIds = uniq(translationIds.concat(keys(get(map, language, []))));
});
forEach(translationIds, translationId => {
const translation: ITranslation = {
messages: new Registry<IMessage>(),
translationId,
};
forEach(languages, lang => {
const message = get(map, [lang, translationId], null);
if (message === null) {
throw new Error(`missing translationId "${translationId}" in ${lang}`);
}
translation.messages.add(lang, { lang, message });
});
translations.push(translation);
});
return translations;
}
Example #9
Source File: scanBricksInStoryboard.ts From next-core with GNU General Public License v3.0 | 6 votes |
export function scanBricksInBrickConf(
brickConf: BrickConf,
isUniq = true
): string[] {
const collection: string[] = [];
collectBricksInBrickConf(brickConf, collection);
const result = collection.filter(
(item) => !item.includes("@") && item.includes("-")
);
return isUniq ? uniq(result) : result;
}
Example #10
Source File: formatQCStopCodons.ts From nextclade with MIT License | 6 votes |
export function formatQCStopCodons<TFunction extends TFunctionInterface>(
t: TFunction,
qcStopCodons?: QcResultStopCodons,
) {
if (!qcStopCodons || qcStopCodons.status === QcStatus.good) {
return undefined
}
const { score, stopCodons, totalStopCodons } = qcStopCodons
const geneList = uniq(stopCodons.map((sc) => sc.geneName)).join(', ')
return t(
'{{totalStopCodons}} misplaced stop codon(s) detected. Affected gene(s): {{geneList}}. QC score: {{score}}',
{
totalStopCodons,
geneList,
score,
},
)
}
Example #11
Source File: FormError.tsx From querybook with Apache License 2.0 | 6 votes |
FormError: React.FC<{
errors: Record<string, any>;
}> = ({ errors }) => {
const errorStrings = useMemo(() => uniq(extractFormikError(errors)), [
errors,
]);
if (errorStrings.length === 0) {
return null;
}
return (
<Message type="error">
{errorStrings.map((error, idx) => (
<div key={idx}>
<span>{error}</span>
<br />
</div>
))}
</Message>
);
}
Example #12
Source File: unionType.ts From genql with MIT License | 6 votes |
unionType = (type: GraphQLUnionType, ctx: RenderContext) => {
let types = type.getTypes()
if (ctx.config?.sortProperties) {
types = types.sort()
}
const fieldStrings = types.map((t) => `on_${t.name}?:${requestTypeName(t)}`)
const commonInterfaces = uniq(flatten(types.map((x) => x.getInterfaces())))
fieldStrings.push(
...commonInterfaces.map((type) => {
return `on_${type.name}?: ${requestTypeName(type)}`
}),
)
fieldStrings.push('__typename?: boolean | number')
ctx.addCodeBlock(
`${typeComment(type)}export interface ${requestTypeName(
type,
)}{\n${fieldStrings.map((x) => ' ' + x).join(',\n')}\n}`,
)
}
Example #13
Source File: unique-id.spec.ts From s-libs with MIT License | 6 votes |
describe('uniqueId()', () => {
it('uses the given prefix', () => {
expect(uniqueId('one').startsWith('one')).toBeTruthy();
expect(uniqueId('two').startsWith('two')).toBeTruthy();
expect(uniqueId('repeat').startsWith('repeat')).toBeTruthy();
expect(uniqueId('repeat').startsWith('repeat')).toBeTruthy();
});
//
// stolen from https://github.com/lodash/lodash
//
it('should generate unique ids', () => {
const actual = times(1000, () => uniqueId());
expect(uniq(actual).length).toBe(actual.length);
});
it('should return a string value when not providing a `prefix`', () => {
expect(typeof uniqueId()).toBe('string');
});
});
Example #14
Source File: parseData.ts From nebula-studio with Apache License 2.0 | 6 votes |
export function getBidrectVertexIds(data) {
const { tables } = data;
// go from nqgl return [{*._dst: id}]
// go from yield edge nqgl return [{_edgesParsedList: srcID: xx, dstID: xx}]
const vertexIds: string[] = [];
tables.forEach((item) => {
item._edgesParsedList.forEach((edge) => {
const { dstID, srcID } = edge;
vertexIds.push(String(dstID));
vertexIds.push(String(srcID));
});
});
return uniq(vertexIds);
}
Example #15
Source File: GroupCompetition.ts From discord-bot with MIT License | 6 votes |
getTeamData(competition: Competition) {
const { participants } = competition;
if (!participants || participants.length === 0) return [];
const teamNames = uniq(participants.map(p => p.teamName));
const teamTally: { [name: string]: number } = Object.fromEntries(teamNames.map(t => [t, 0]));
participants.forEach(p => {
if (!p.teamName) return;
teamTally[p.teamName] = teamTally[p.teamName] + p.progress.gained;
});
const teamStandings = Object.entries(teamTally).map(t => ({ name: t[0], totalGained: t[1] }));
// Sort teams by most total gained
return teamStandings
.sort((a, b) => b.totalGained - a.totalGained)
.map(t => `${t.name} - **${toKMB(t.totalGained)}**`);
}
Example #16
Source File: competition.service.ts From wise-old-man with MIT License | 6 votes |
function getTeamsCSV(details: CompetitionDetails): string {
const teamNames = uniq(details.participants.map(p => p.teamName));
const teamMap = Object.fromEntries(teamNames.map(t => [t, { name: t, participants: [] }]));
details.participants.forEach(p => {
teamMap[p.teamName].participants.push(p);
});
const teamsList = Object.values(teamMap).map(t => {
// Sort participants by most gained, and add team rank
const sortedParticipants = t.participants
.sort((a, b) => b.progress.gained - a.progress.gained)
.map((p, i) => ({ ...p, teamRank: i + 1 }));
const totalGained = t.participants.map(p => p.progress.gained).reduce((a, c) => a + c);
const avgGained = totalGained / t.participants.length;
return { ...t, participants: sortedParticipants, totalGained, avgGained };
});
// Sort teams by most total gained
const data = teamsList.sort((a, b) => b.totalGained - a.totalGained).map((t, i) => ({ ...t, rank: i + 1 }));
const columns = [
{ header: 'Rank', value: (_, index) => index + 1 },
{ header: 'Name', value: row => row.name },
{ header: 'Players', value: row => row.participants.length },
{ header: 'Total Gained', value: row => row.totalGained },
{ header: 'Average Gained', value: row => row.avgGained },
{ header: 'MVP', value: row => row.participants[0].displayName }
];
const headers = columns.map(c => c.header).join(',');
const rows = data.map((p, i) => columns.map(c => c.value(p, i)).join(','));
return [headers, ...rows].join('\n');
}
Example #17
Source File: index.ts From free-swagger with MIT License | 6 votes |
createTagsByPaths = (
paths: OpenAPIV2.PathsObject
): OpenAPIV2.TagObject[] =>
// @ts-ignore
sortBy(
uniq(
flattenDeep(
Object.values(paths).map((item: OpenAPIV2.PathItemObject) =>
Object.values(item).map(
(item: OpenAPIV2.OperationObject) => item.tags
)
)
).filter(Boolean)
)
).map((item) => ({ name: item }))
Example #18
Source File: FailureInputContainer.tsx From calculate-my-odds with MIT License | 6 votes |
componentDidUpdate(prevProps: Props) {
if (this.props.tables !== prevProps.tables) {
const items = flatten(this.props.tables.map(x => x.items));
const newFailures = {...this.state.rootFailure};
this.uniqueItemNames = uniq(items.map(x => x.name));
this.uniqueItemNames.sort();
updateFailureFromProbabilityTables(newFailures, new Set(this.uniqueItemNames), this.props.nameChange);
this.setState({
rootFailure: newFailures
});
}
}
Example #19
Source File: pivot-data-set.ts From S2 with MIT License | 6 votes |
/**
* 自定义度量组位置值
* @param customValueOrder 用户配置度量组位置,从 0 开始
* @param fields Rows || Columns
*/
private handleCustomMeasuresOrder(
customValueOrder: number,
fields: string[],
) {
const newFields = uniq([...fields]);
if (fields.length >= customValueOrder) {
newFields.splice(customValueOrder, 0, EXTRA_FIELD);
return newFields;
}
// 当用户配置的度量组位置大于等于度量组数量时,默认放在最后
return [...newFields, EXTRA_FIELD];
}
Example #20
Source File: GoalInputContainer.tsx From calculate-my-odds with MIT License | 6 votes |
componentDidUpdate(prevProps: Props) {
if (this.props.tables !== prevProps.tables) {
const items = flatten(this.props.tables.map(x => x.items));
const newGoals = {...this.state.rootGoal};
this.uniqueItemNames = uniq(items.map(x => x.name));
this.uniqueItemNames.sort();
updateGoalFromProbabilityTables(newGoals, new Set(this.uniqueItemNames), this.props.nameChange);
this.setState({
rootGoal: newGoals
});
}
}
Example #21
Source File: utils.ts From prism-frontend with MIT License | 6 votes |
convertToTableData = (result: ExposedPopulationResult) => {
const {
key,
groupBy,
statistic,
featureCollection: { features },
} = result;
const fields = uniq(features.map(f => f.properties && f.properties[key]));
const featureProperties = features.map(feature => {
return {
[groupBy]: feature.properties?.[groupBy],
[key]: feature.properties?.[key],
[statistic]: feature.properties?.[statistic],
};
});
const rowData = mapValues(_groupBy(featureProperties, groupBy), k => {
return mapValues(_groupBy(k, key), v =>
parseInt(
v.map(x => x[statistic]).reduce((acc, value) => acc + value),
10,
),
);
});
const groupedRowData = Object.keys(rowData).map(k => {
return {
[groupBy]: k,
...rowData[k],
};
});
const groupedRowDataWithAllLabels = groupedRowData.map(row => {
const labelsWithoutValue = difference(fields, keysIn(row));
const extras = labelsWithoutValue.map(k => ({ [k]: 0 }));
return extras.length !== 0 ? assign(row, ...extras) : row;
});
const headlessRows = groupedRowDataWithAllLabels.map(row => {
// TODO - Switch between MAX and SUM depending on the polygon source.
// Then re-add "Total" to the list of columns
// const total = fields.map(f => row[f]).reduce((a, b) => a + b);
// return assign(row, { Total: total });
return row;
});
const columns = [groupBy, ...fields]; // 'Total'
const headRow = zipObject(columns, columns);
const rows = [headRow, ...headlessRows];
return { columns, rows };
}
Example #22
Source File: index.tsx From hub with Apache License 2.0 | 6 votes |
getResourceKinds = (data: string): string[] => {
const kinds = data.match(KIND);
if (kinds) {
const cleanKinds = kinds.map((kind: string) => {
const parts = kind.split(':');
return parts[1].replaceAll('"', '').trim();
});
return uniq(compact(cleanKinds));
}
return [];
}
Example #23
Source File: completion-items-literals-spec.ts From ui5-language-assistant with Apache License 2.0 | 5 votes |
describe("the UI5 language assistant Code Completion Services", () => {
let ui5SemanticModel: UI5SemanticModel;
before(async () => {
//TODO: use 1.71.x
ui5SemanticModel = await generateModel({
version: "1.74.0",
modelGenerator: generate,
});
});
it("will get completion values for boolean value", () => {
const xmlSnippet = `<mvc:View
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
busy="⇶">`;
const suggestions = getSuggestions(xmlSnippet, ui5SemanticModel);
const suggestionsDetails = map(suggestions, (suggestion) => ({
label: suggestion.label,
replacedText: getTextInRange(xmlSnippet, suggestion.textEdit?.range),
newText: suggestion.textEdit?.newText,
}));
const suggestionKinds = uniq(
map(suggestions, (suggestion) => suggestion.kind)
);
expect(suggestionsDetails).to.deep.equalInAnyOrder([
{ label: "false", replacedText: `""`, newText: `"false"` },
{ label: "true", replacedText: `""`, newText: `"true"` },
]);
expect(suggestionKinds).to.deep.equal([CompletionItemKind.Constant]);
});
it("will get completion values for UI5 boolean value when the cursor is in the middle of a name", () => {
const xmlSnippet = `<mvc:View
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
busy="t⇶a">`;
const suggestions = getSuggestions(xmlSnippet, ui5SemanticModel);
const suggestionsDetails = map(suggestions, (suggestion) => ({
label: suggestion.label,
replacedText: getTextInRange(xmlSnippet, suggestion.textEdit?.range),
newText: suggestion.textEdit?.newText,
}));
const suggestionKinds = uniq(
map(suggestions, (suggestion) => suggestion.kind)
);
expect(suggestionsDetails).to.deep.equalInAnyOrder([
{ label: "true", replacedText: `"ta"`, newText: `"true"` },
]);
expect(suggestionKinds).to.deep.equal([CompletionItemKind.Constant]);
});
});
Example #24
Source File: ModNameSelect.tsx From ow-mod-manager with MIT License | 5 votes |
ModNameSelect: React.FunctionComponent<Props> = ({
value,
onChange,
logLines,
}) => {
const styles = useStyles();
const [modNames, setModNames] = useState<string[]>([]);
useEffect(() => {
debugConsole.log('useEffect: ModNameSelect set mod names');
setModNames(uniq(logLines.map((line) => line.modName)));
}, [logLines]);
const handleModNameChange = ({
target,
}: React.ChangeEvent<{
name?: string | undefined;
value: unknown;
}>) => {
onChange(target.value as string);
};
return (
<Select
variant="outlined"
margin="dense"
className={styles.root}
value={value}
onChange={handleModNameChange}
displayEmpty
>
<MenuItem value={''}>{logsText.allMods}</MenuItem>
{modNames.map((modName) => (
<MenuItem value={modName} key={modName}>
{modName}
</MenuItem>
))}
</Select>
);
}
Example #25
Source File: tag-form.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
TagForm = ({ visible, machine, onCancel }: IProps) => {
const currentOrg = orgStore.useStore((s) => s.currentOrg);
const nodeLabels = clusterDashboardStore.useStore((s) => s.nodeLabels);
const { getNodeLabels } = clusterDashboardStore.effects;
const { updaterMachineLabels } = machineStore.effects;
React.useEffect(() => {
visible && getNodeLabels();
}, [getNodeLabels, visible]);
const handelSubmit = (values: { labels: string[]; customLabels: string }) => {
// 组合自定义标签和选项标签,去重
const { labels, customLabels = [] } = values;
const savedLabels = uniq(labels.concat(customLabels));
machine &&
updaterMachineLabels({
labels: savedLabels,
hosts: [machine.ip],
clusterName: machine.clusterName,
orgID: currentOrg.id,
});
onCancel();
};
const chosenLabels = machine ? machine.labels.split(',') : [];
const normalLabels: string[] = [];
const customLabels: string[] = [];
chosenLabels.forEach((item: string) => {
if (item) {
if (find(nodeLabels, { label: item })) {
normalLabels.push(item);
} else {
customLabels.push(item);
}
}
});
const fieldsList = [
{
label: i18n.t('label'),
name: 'labels',
required: false,
getComp: () => (
<LabelSelector
labelOptions={nodeLabels.filter((l) => !l.isPrefix).map((l) => ({ ...l, value: l.label, name: l.label }))}
/>
),
},
{
label: i18n.t('Custom label'),
name: 'customLabels',
required: false,
getComp: () => <CustomLabel />,
rules: [{ validator: checkTagLabels }],
},
];
const machineIp = machine?.ip;
return (
<>
<FormModal
width={620}
title={i18n.t('cmp:set labels of {ip}', { ip: machineIp })}
fieldsList={fieldsList}
visible={visible}
formData={{ labels: normalLabels, customLabels }}
onOk={handelSubmit}
onCancel={onCancel}
/>
</>
);
}
Example #26
Source File: pivot-data-set.ts From S2 with MIT License | 5 votes |
public processDataCfg(dataCfg: S2DataConfig): S2DataConfig {
const { data, meta = [], fields, sortParams = [], totalData } = dataCfg;
const { columns, rows, values, valueInCols, customValueOrder } = fields;
let newColumns = columns;
let newRows = rows;
if (valueInCols) {
newColumns = this.isCustomMeasuresPosition(customValueOrder)
? this.handleCustomMeasuresOrder(customValueOrder, newColumns)
: uniq([...columns, EXTRA_FIELD]);
} else {
newRows = this.isCustomMeasuresPosition(customValueOrder)
? this.handleCustomMeasuresOrder(customValueOrder, newRows)
: uniq([...rows, EXTRA_FIELD]);
}
const valueFormatter = (value: string) => {
const currentMeta = find(meta, ({ field }: Meta) => field === value);
return get(currentMeta, 'name', value);
};
// 虚拟列字段,为文本分类字段
const extraFieldName =
this.spreadsheet?.options?.cornerExtraFieldText || i18n('数值');
const extraFieldMeta: Meta = {
field: EXTRA_FIELD,
name: extraFieldName,
formatter: (value: string) => valueFormatter(value),
};
const newMeta: Meta[] = [...meta, extraFieldMeta];
const newData = this.standardTransform(data, values);
const newTotalData = this.standardTransform(totalData, values);
return {
data: newData,
meta: newMeta,
fields: {
...fields,
rows: newRows,
columns: newColumns,
values,
},
totalData: newTotalData,
sortParams,
};
}
Example #27
Source File: main.ts From EIP-Bot with Creative Commons Zero v1.0 Universal | 5 votes |
_main_ = async () => {
// Verify correct environment and request context
requireEvent();
const pr = await requirePr();
// Collect the changes made in the given PR from base <-> head for eip files
const files = await requireFiles(pr);
let results: Results = [];
for await (const file of files) {
try {
const dirtyTestResults = await testFile(file);
const testResults = await purifyTestResults(dirtyTestResults);
results.push(testResults);
} catch (err: any) {
processError(err, {
gracefulTermination: (message) => {
results.push({
filename: file.filename,
successMessage: message,
type: ChangeTypes.ambiguous
});
},
requirementViolation: (message) => {
results.push({
filename: file.filename,
errors: [message],
type: ChangeTypes.ambiguous
});
},
unexpectedError: (message, data) => {
console.log(JSON.stringify(data, null, 2));
message = `An unexpected error occurred (cc ${MAINTAINERS().join(
", "
)}): ${message}`;
results.push({
filename: file.filename,
errors: [message],
type: ChangeTypes.ambiguous
});
}
});
}
}
// updates labels to be as expected
const expectedLabels = _.uniq(_.map(results, "type"));
await PullRequestUseCases.updateLabels(expectedLabels);
if (!results.filter((res) => res.errors).length) {
const commentMessage = getCommentMessage(
results,
"All tests passed; auto-merging..."
);
await PullRequestUseCases.postComment(commentMessage);
console.log(commentMessage);
return;
}
const commentMessage = getCommentMessage(results);
// to avoid annoying people, it's best to only do this while running prod
if (isProd()) {
await PullRequestUseCases.postComment(commentMessage);
await requestReviewers(
uniq(results.flatMap((res) => res.mentions).filter(Boolean) as string[])
);
}
console.log(commentMessage);
return setFailed(commentMessage);
}
Example #28
Source File: custom-tree-pivot-data-set.ts From S2 with MIT License | 5 votes |
processDataCfg(dataCfg: S2DataConfig): S2DataConfig {
// 自定义行头有如下几个特点
// 1、rows配置必须是空,需要额外添加 $$extra$$ 定位数据(标记指标的id)
// 2、要有配置 fields.rowCustomTree(行头结构)
// 3、values 不需要参与计算,默认就在行头结构中
dataCfg.fields.rows = [EXTRA_FIELD];
dataCfg.fields.valueInCols = false;
const { data, ...restCfg } = dataCfg;
const { values } = dataCfg.fields;
// 将源数据中的value值,映射为 $$extra$$,$$value$$
// {
// province: '四川', province: '四川',
// city: '成都', => city: '成都',
// price='11' price='11'
// $$extra$$=price
// $$value$$=11
// 此时 province, city 均配置在columns里面
// }
const transformedData = [];
forEach(data, (dataItem) => {
if (isEmpty(intersection(keys(dataItem), values))) {
transformedData.push(dataItem);
} else {
forEach(values, (value) => {
if (has(dataItem, value)) {
transformedData.push({
...dataItem,
[EXTRA_FIELD]: value,
[VALUE_FIELD]: dataItem[value],
});
}
});
}
});
return {
data: uniq(transformedData),
...restCfg,
};
}
Example #29
Source File: next.config.ts From nextclade with MIT License | 5 votes |
transpilationListProd = uniq([
// prettier-ignore
...transpilationListDev,
'debug',
'lodash',
'semver',
])