Quiero seleccionar columnas Prisma dinámicamente, obtengo esto del cliente:
['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc']Quiero cambiarlo a algo como esto:
{id: true, createdAt: true, updatedAt: true, Order: {select: {id: true, Item: {select: {id: true, desc: true}}}}para que pueda usarlo en la consulta de Prisma como:
prisma.sales.findMany({where: {id: {_eq: 1}}, select: {id: true, createdAt: true, updatedAt: true, Order: {select: {id: true, Item: {select: {id: true, desc: true}}}}}})Puede crear una función recursiva simple para crear un objeto y completar las propiedades anidadas:
const objPaths = ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc']; function buildObject(paths) { const result = {}; for (const path of paths) { const pathParts = path.split("."); if (pathParts.length > 1) { populateNested(result, pathParts, 0); } else { result[path] = true; } } return result; } function populateNested(parent, paths, currPathIndex) { if (currPathIndex === paths.length - 1) { parent[paths[currPathIndex]] = true; } else { let currObj = {select: {}}; if (parent[paths[currPathIndex]]) { currObj = parent[paths[currPathIndex]]; } parent[paths[currPathIndex]] = currObj; populateNested(currObj.select, paths, currPathIndex + 1); } } console.log(JSON.stringify(buildObject(objPaths), null, 2));