mirror of
https://github.com/strapi/strapi.git
synced 2025-09-29 02:11:45 +00:00
66 lines
1.8 KiB
JavaScript
66 lines
1.8 KiB
JavaScript
![]() |
// NOTE: this function is for adding a __temp_key__ key to each object of a repeatable component
|
||
|
// in order to have a unique identifier for the DnD
|
||
|
|
||
|
import { get } from 'lodash';
|
||
|
|
||
|
const getType = (schema, attrName) => get(schema, ['attributes', attrName, 'type'], '');
|
||
|
const getOtherInfos = (schema, arr) => get(schema, ['attributes', ...arr], '');
|
||
|
|
||
|
const formatComponentData = (data, ct, composSchema) => {
|
||
|
const recursiveFormatData = (data, schema) => {
|
||
|
return Object.keys(data).reduce((acc, current) => {
|
||
|
const type = getType(schema.schema, current);
|
||
|
const value = get(data, current);
|
||
|
const compoUid = getOtherInfos(schema.schema, [current, 'component']);
|
||
|
const isRepeatable = getOtherInfos(schema.schema, [current, 'repeatable']);
|
||
|
|
||
|
if (!value) {
|
||
|
acc[current] = value;
|
||
|
|
||
|
return acc;
|
||
|
}
|
||
|
|
||
|
if (type === 'dynamiczone') {
|
||
|
acc[current] = value.map(componentValue => {
|
||
|
const formattedData = recursiveFormatData(
|
||
|
componentValue,
|
||
|
composSchema[componentValue.__component]
|
||
|
);
|
||
|
|
||
|
console.log({ formattedData });
|
||
|
|
||
|
return formattedData;
|
||
|
});
|
||
|
|
||
|
return acc;
|
||
|
}
|
||
|
|
||
|
if (type === 'component') {
|
||
|
let formattedValue;
|
||
|
|
||
|
if (isRepeatable) {
|
||
|
formattedValue = value.map((obj, i) => {
|
||
|
const newObj = { ...obj, __temp_key__: i };
|
||
|
|
||
|
return recursiveFormatData(newObj, composSchema[compoUid]);
|
||
|
});
|
||
|
} else {
|
||
|
formattedValue = recursiveFormatData(value, composSchema[compoUid]);
|
||
|
}
|
||
|
|
||
|
acc[current] = formattedValue;
|
||
|
|
||
|
return acc;
|
||
|
}
|
||
|
|
||
|
acc[current] = value;
|
||
|
|
||
|
return acc;
|
||
|
}, {});
|
||
|
};
|
||
|
|
||
|
return recursiveFormatData(data, ct);
|
||
|
};
|
||
|
|
||
|
export default formatComponentData;
|