Want to convert a nested object to query parameter for attaching to url

let obj = {
  user: {
    first_name: 'Srini',
    last_name: 'Raman',
    gender: 'male',
    dob: '1992-08-02',
    address_attributes: {
      city: 'San Diego',
      state: 'CA',
      zip: 92127,
      country: 'USA',
      latitude: 37.257009,
      longitude: -120.050767
    }
  }
};

let getPairs = (obj, keys = []) =>
  Object.entries(obj).reduce((pairs, [key, value]) => {
    if (typeof value === 'object')
      pairs.push(...getPairs(value, [...keys, key]));
    else
      pairs.push([[...keys, key], value]);
    return pairs;
  }, []);

let x = getPairs(obj)
  .map(([[key0, ...keysRest], value]) =>
    `${key0}${keysRest.map(a => `[${a}]`).join('')}=${value}`)
  .join('&');
console.log(x);

Here is a TypeScript implementation if someone needs it.


const testObject = {
  "user": {
    "first_name": "Srini",
    "last_name": "Raman",
    "gender": "male",
    "dob": "1992-08-02",
    "address_attributes": {
      "city": "San Diego",
      "state": "CA",
      "zip": 92127,
      "country": "USA",
      "latitude": 37.257009,
      "longitude": -120.050767
    }
  }
}

interface ObjectToQueryStringHelperObject {
  keyPath: Array<string>;
  value: boolean | number | string;
}

function objectToQueryStringHelper(
  object: any,
  path: Array<string> = [],
  result: Array<ObjectToQueryStringHelperObject> = []
): Array<ObjectToQueryStringHelperObject> {
  return Object.entries(object).reduce((acc, [key, value]) => {
    if (!_.isNil(value) || !_.isEmpty(value)) {
      _.isObject(value) ?
        acc.push(...objectToQueryStringHelper(value, [...path, key], result)) :
        acc.push({ keyPath: [...path, key], value });
    }
    return acc;
  }, []);
}

export function objectToQueryString(object: any): string {
  const simplifiedData = objectToQueryStringHelper(object);
  const queryStrings = simplifiedData.map(({ keyPath: [firstKey, ...otherKeys], value }) => {
    const nestedPath = otherKeys.map(key => `[${key}]`).join('');
    return `${firstKey}${nestedPath}=${!_.isNil(value) ? encodeURI(`${value}`) : ''}`
  })
  return queryStrings.join('&');
}

console.log(objectToQueryString(testObject))