gqty
Version:
The No-GraphQL Client for TypeScript
35 lines (33 loc) • 993 B
JavaScript
const pick = (schema, selections) => {
const result = {};
for (const { ancestry } of selections) {
let srcNode = schema;
for (const { key, input } of ancestry) {
if (srcNode == null) break;
if (typeof srcNode[key] === "function") {
srcNode = srcNode[key](input == null ? void 0 : input.values);
} else {
srcNode = srcNode[key];
}
}
if (srcNode !== void 0) {
let dstNode = result;
for (let i = 0; i < ancestry.length - 1; i++) {
if (!dstNode) break;
const { key } = ancestry[i];
const { key: nextKey } = ancestry[i + 1];
if (typeof nextKey === "number" && (!dstNode[key] || !Array.isArray(dstNode[key]))) {
dstNode[key] = [];
} else if (!dstNode[key]) {
dstNode[key] = {};
}
dstNode = dstNode[key];
}
if (dstNode) {
dstNode[ancestry[ancestry.length - 1].key] = srcNode;
}
}
}
return result;
};
export { pick };