My array contains objects with elements that are dependent on each other.
To properly store this data in a database, I need to order the array by importance (based on parent dependency) and update all children's parent
property with the corresponding parent id
.
Here is an example of the array structure:
[
{
"id": 1,
"email": "example1@example.com",
"parent": "parent1@example.com"
},
{
"id": 2,
"email": "example2@example.com",
"parent": null
},
{
"id": 3,
"email": "example3@example.com",
"parent": "parent2@example.com"
},
{
"id": 4,
"email": "example4@example.com",
"parent": "parent3@example.com"
},
...
]
Below is a graphical representation of the dependencies:
https://i.sstatic.net/02P88.png
Expected result after ordering by dependency (parent level):
[
{
"id": 2,
"email": "example2@example.com",
"parent": null
},
{
"id": 3,
"email": "example3@example.com",
"parent": 2
},
{
"id": 1,
"email": "example1@example.com",
"parent": 3
},
{
"id": 4,
"email": "example4@example.com",
"parent": 1
},
...
]
To assign respective parent id
, I am using the following method:
let users = [
{
"id": 1,
"email": "user1@example.com",
"parent": "parent1@example.com"
},
{
"id": 2,
"email": "user2@example.com",
"parent": null
},
{
"id": 3,
"email": "user3@example.com",
"parent": "parent2@example.com"
},
{
"id": 4,
"email": "user4@example.com",
"parent": "parent3@example.com"
}
];
users = users.map(user => {
user.parent = _.findIndex(users, i => user.parent === i.email);
return user;
});
P.S:
In this scenario, the term importance
signifies the hierarchy of parent
.
Therefore, it is essential to first list the parents followed by their children, grandchildren, etc.
I apologize if my explanation is lacking clarity. Feel free to ask any questions for further clarification.