0
The array Javascript below is the result of a query Mysql:
json-database.json
[
{
"id": 1,
"node_name": "SP2 - Virtual Private Serve Product",
"children_name": "Virtual Private Server CPU",
"node_id": 1
},
{
"id": 1,
"node_name": "SP2 - Virtual Private Serve Product",
"children_name": "Virtual Private Server Hard Disk",
"node_id": 1
},
{
"id": 1,
"node_name": "SP2 - Virtual Private Serve Product",
"children_name": "Virtual Private Server RAM",
"node_id": 1
},
{
"id": 2,
"node_name": "SP2 - Virtual Private Serve Product",
"children_name": "Virtual Private Server CPU",
"node_id": 2
},
{
"id": 2,
"node_name": "SP2 - Virtual Private Serve Product",
"children_name": "Virtual Private Server Hard Disk",
"node_id": 2
},
{
"id": 2,
"node_name": "SP2 - Virtual Private Serve Product",
"children_name": "Virtual Private Server RAM",
"node_id": 2
}
]
Mysql query:
SELECT N.id, N.name AS node_name, C.id AS children_id, C.name AS children_name, C.node_id
FROM tab_nodes AS N
INNER JOIN tab_nodes_children AS C
ON N.id = C.node_id
I need to convert the array into a Javascript object with the structure down below:
nodes = [
{
id: 1,
name: 'SP2 - Virtual Private Serve Product',
children: [
{
id: 1,
name: 'Virtual Private Server CPU'
},
{
id: 2,
name: 'Virtual Private Server Hard Disk'
},
{
id: 3,
name: 'Virtual Private Server CPU'
},
]
},
{
id: 2,
name: 'SP2 - Virtual Private Serve Product',
children: [
{
id: 4,
name: 'Virtual Private Server CPU'
},
{
id: 5,
name: 'Virtual Private Server Hard Disk'
},
{
id: 6,
name: 'Virtual Private Server CPU'
},
]
},
]
I’m trying to use the reduce with Object.assign, but it’s going wrong.
You cannot do this, since your array contains several objects with the same signature, which would create a property collision problem. What is your motivation for wanting to do something like this?
– Luiz Felipe
I put repeated values in this test, but in reality the values will be different. I am developing an application using v7 angular which, in one of the components, will have a tree view. For this I am using the following package:https://angular2-tree.readme.io/ To assemble the desired structure I need to follow the pattern recommended by them
– Leonardo Vinicius