9

Hi I need to construct to url request with query parameter, I have a nested object with the key and values, like below

 "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
    }
}


i need to get a query parameter like

user[first_name]=Srini&user[last_name]=Raman&user[address_attributes][city]=San Diego&user[address_attributes][state]=CA
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Srinivasan Raman
  • 441
  • 1
  • 4
  • 7

3 Answers3

15

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);
junvar
  • 11,151
  • 2
  • 30
  • 46
4

You can use the qs package.

Their stringify method seems to do exactly what you want.

Usage example:

window.addEventListener("load", () => {
  const 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
      }
    }
  };

  console.log(Qs.stringify(obj, { encode: false }));
}, {
  once: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.11.0/qs.min.js"></script>
  • please add more info from the mentioned site in your answer. Otherwise its a "link only" answer, which might get deleted by the community. – Logemann Jan 14 '22 at 19:29
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30820290) – Luca Kiebel Jan 18 '22 at 10:52
  • Very nice and easy library to use, I recommand, thanks for sharing – raphael-allard Apr 11 '22 at 10:03
  • That works but is incredibly bloated IMHO for the job. Looks like `query-string` module now does serialize nested objects for a much smaller payload. – Philippe Jan 03 '23 at 05:28
2

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))
fr1sk
  • 204
  • 2
  • 13