Skip to content Skip to sidebar Skip to footer

How Can I Merge 2 Dot Notation Strings To A Graphql Query String

I'm trying to merge 2 dot notation strings into a GrahQL query with only javascript (it can be ES6/typescript). For example, let say that I have an array of strings [ 'firstNam

Solution 1:

Revised Answer

Based on your revised question and requirements, here's a revised answer. This will recursively build an object from nested dot notations, and then leverage JSON.stringify to build the query string (with some string manipulations);

functionbuildQuery(...args) {
  constset = (o = {}, a) => {
    const k = a.shift();
    o[k] = a.length ? set(o[k], a) : null;
    return o;
  }
  
  const o = args.reduce((o, a) =>set(o, a.split('.')), {});
  
  returnJSON.stringify(o)
    .replace(/\"|\:|null/g, '')
    .replace(/^\{/, '')
    .replace(/\}$/, '');
}

const query = buildQuery(
  'firstName', 
  'lastName', 
  'billing.address.street', 
  'billing.address.zip', 
  'shipping.address.street', 
  'shipping.address.zip'
);

console.log(query);

Original Answer

I would suggest converting the individual dot notation strings into an object first, and then converting the object to a string.

function buildQuery(...args) {
    let q = {};

    args.forEach((arg) => {
        const [ o, a ] = arg.split('.');
        q[o] = q[o] || [];
        if (a) q[o] = q[o].concat(a);
    });

    return Object.keys(q).map((k) => {
        returnq[k].length ? `${k} \{ ${q[k].join(', ')} \}` : k;
    }).join(', ');
}

const query = buildQuery('person.name', 'person.email', 'street.name', 'street.zip');
console.log(query);
//"person { name, email }, street { name, zip }"

Post a Comment for "How Can I Merge 2 Dot Notation Strings To A Graphql Query String"