I have an array of objects:
const flatData = [
{
"name": "Fish 1",
"price": 15
},
{
"name": "Super Fish 1",
"price": 12,
"family": "Super Fish family"
},
{
"name": "Super Fish 2",
"price": 17,
"family": "Super Fish family"
},
{
"name": "Super Fish 3",
"price": 16,
"family": "Super Fish family"
},
{
"name": "Awful legged Fish 1",
"price": 22,
"family": "Awful Fish family",
"sub_family": "Awful Fish with legs"
},
{
"name": "Awful legged Fish 2",
"price": 15,
"family": "Awful Fish family",
"sub_family": "Awful Fish with legs"
},
{
"name": "Awful legged Fish 3",
"price": 23,
"family": "Awful Fish family",
"sub_family": "Awful Fish with legs"
},
{
"name": "Awful blue dotted Fish 1",
"price": 10,
"family": "Awful Fish family",
"sub_family": "Awful Fish with blue dots"
},
{
"name": "Awful blue dotted Fish 2",
"price": 11,
"family": "Awful Fish family",
"sub_family": "Awful Fish with blue dots"
}
]
And I wanted to convert it to a nested array of objects:
const nestedData = [
{
"id": "0",
"name": "Fish 1",
"price": 15
},
{
"id": "1",
"name": "Super Fish family",
"selected": -1,
"family": [
{
"id": "0",
"name": "Super Fish 1",
"price": 12
},
{
"id": "1",
"name": "Super Fish 2",
"price": 17
},
{
"id": "2",
"name": "Super Fish 3",
"price": 16
}
]
},
{
"id": "2",
"name": "Awful Fish family",
"selected": -1,
"family": [
{
"id": "0",
"name": "Awful Fish with legs",
"selected": -1,
"family": [
{
"id": "0",
"name": "Awful legged Fish 1",
"price": 22
},
{
"id": "1",
"name": "Awful legged Fish 2",
"price": 15
},
{
"id": "2",
"name": "Awful legged Fish 3",
"price": 23
}
]
},
{
"id": "1",
"name": "Awful Fish with blue dots",
"selected": -1,
"family": [
{
"id": "0",
"name": "Awful blue dotted Fish 1",
"price": 10
},
{
"id": "1",
"name": "Awful blue dotted Fish 2",
"price": 11
}
]
}
]
}
]
I thought I could break the problem down into a series of less complicated problems but I’m stuck at this step. I found solutions based on splitting a string but my flat file is different. The presence of “family” and “sub_family” and I can deduce depth information from one single value…
Is there a js library that would make this easier?