Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 317
Srinivasan Raman Avatar asked Mar 04 '23 23:03

Srinivasan Raman


1 Answers

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);
like image 93
junvar Avatar answered May 01 '23 15:05

junvar