I have this object:
{
name: "Gold's Gym Venice",
"categories[0].alias": "gyms",
"categories[0].title": "Gyms",
"categories[1].alias": "healthtrainers",
"categories[1].title": "Trainers",
"location.state": "CA",
"location.city": "Venice",
"location.zip_code": "90291",
"location.display_address[0]": "360 Hampton Dr",
"location.display_address[1]": "Venice, CA 90291"
}
… and am trying to transform it into this:
{
name: "Gold's Gym Venice",
categories: [
{ alias: "gyms", title: "Gyms" },
{ alias: "healthtrainers", title: "Trainers" }
],
location: {
state: "CA",
city: "Venice",
zip_code: "90291",
display_address: [ "360 Hampton Dr", "Venice, CA 90291" ]
}
}
I tried both of these answers. Each gives slightly different output—the second one gets closer—but neither handles keys with square bracketed numbers/array positions properly.
What’s the best way to handle this?
2
Answers
I tried ChatGPT after this question was answered and it came up with a very robust, elegant solution after a few tries.
I find this solution to be more concise and equally readable compared to the accepted answer.
Another, more verbose approach can be viewed in this answer's edit history.
I think we can use the method from this answer, here is an example code for the example you provided: