I have this JSON response, I want to unflatten it, but every possible unflatten library just append it to array, I want to highlight to have 3 object like shown, is there any easier way?
{
"highlights.id": ["9ab80883-e8eb-4710-9818-e476fc32e356", "824ff2a0-1f17-44b7-b99f-ce227af12ea7", "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe", ],
"highlights.key": ["0", "1", "2"],
"highlights.value": ['16" Pedestal Fan', "High Quality Metal Grill ", "Heavy Duty Motor with 2000 RPM", ],
"highlights.productId": ["655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", ],
"highlights.createdAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ],
"highlights.updatedAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ]
}
I want something like
highlights:[ {// id, key, value, productId}, {}, {}]
But I’m getting
highlights:{ id:[], productId:[], key:[], value:[]
4
Answers
Use Array.map
You can use
.map
function to loop through the keys just to make it consistent and return a new object, the way you want it, then store in to the new highlights array.DEMO
Dynamic solution:
If you want it to be more dynamic you can loop through the keys of your JSON object as well
Sorry but it’s not possible to convert into
because there is an object inside your array
highlights
. You must declare an object key. I have an idea for your solution by usingClass
andconstructor
If you meant
then my solution to you is…
The difference between class and object in this use case is naming convention such that object allows you to use
spacing for naming key
while you can’t do that inconstructor
(either_
or capital keys to make it easier to differentiate)NOTE : While updating object in javascript, [.] where . is dynamic key without square bracket it will be a static key.
You can do it with iterate it through
data
array. If you want a simple answer, try this: