I have a list of paths with ids and I need to convert it into complete JSON object.
I'm trying to convert this:
[
{
"id": 1,
"name": "Electronics",
"path": "Electronics"
},
{
"id": 2,
"name": "Laptops & PC",
"path": "Electronics > Laptops & PC"
},
{
"id": 7,
"name": "Phones & Accessories",
"path": "Electronics > Phones & Accessories"
},
{
"id": 8,
"name": "Smartphones",
"path": "Electronics > Phones & Accessories > Smartphones"
},
{
"id": 9,
"name": "Android",
"path": "Electronics > Phones & Accessories > Smartphones > Android"
},
{
"id": 10,
"name": "iOS",
"path": "Electronics > Phones & Accessories > Smartphones > iOS"
}
]
to something like this:
let output = [
{'Electronics' : {id: 1, name: "electronics", path: "electronics", children: [
{'Laptops & PC' : {id: 2, name: "Laptops & PC",path: "Electronics > Laptops & PC", children: []}},
{'Phone & Accessories': {id: 7, name: "Phones & Accessories", path: "Electronics > Phones & Accessories", children: [
{'Smartphones': {id: 8, name: "Smartphones", path: "Electronics > Phones & Accessories > Smartphones", children: [
{'Android': {id: 9, name: "Android", path: "Electronics > Phones & Accessories > Smartphones > Android", children: []}},
{'iOS': {id: 10, name: 'iOS', path: "Electronics > Phones & Accessories > Smartphones > iOS", children: []}}
]
}}
]}}
]}}
];
I got a solution similar to this on Stackoverflow (How to convert an array of paths into JSON structure?) But I couldn't add extra properties to the object using those answers.
Can somebody please help me?
'Electronics'have the common path prefix'Electronics >').