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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With