I have an object of objects of a company’s hierarchy selection, for example:
{
1: { division: "division1" },
2: { division: "division2" },
11: { division: "division2", branch: "branch2" },
41: { division: "division2", branch: "branch2", department: "department2" },
100: { division: "division2", branch: "branch2", department: "department10" },
102: { division: "division2", branch: "branch3" },
130: { division: "division17" },
144: { division: "division17" , branch: "branch22" },
200: { division: "division50" }
}
And I need to get the unique objects but most detailed ones. So the above example should result in:
{
1: { division: "division1" },
41: { division: "division2", branch: "branch2", department: "department2" },
100: { division: "division2", branch: "branch2", department: "department10" },
102: { division: "division2", branch: "branch3" },
144: { division: "division17" , branch: "branch22" },
200: { division: "division50" }
}
These are selections from 3 dropdowns, each selection holds the data of the entire hierarchy up to that item (The hierarchy is division
> branch
> department
). So if a user selects division2
then branch2
, it will add both { division: "division2" }
and { division: "division2", branch: "branch2" }
but I only need the most detailed one, { division: "division2", branch: "branch2" }
in this case.
*Edit: It is not necessary to keep the original keys
How can I do that?
3
Answers
I am assuming by most detailed you mean the object containing the most properties, hence being the most detailed object?
In that case you could possible count the amount of keys in the object, and only grab the object with the most keys, hence grabbing the most detailed object.
EDIT: If the objects will always have at least the
division
key value, you could execute these steps:division
. If there are no matches, it’s unique and the most detailed already.{ division: "val1", key2: "val2"}
gets returned, and{ division: "val1" }
does not.You should end up with objects that have unique division values, and are the most detailed objects.
You could build a tree with known values and filter the array by looking to values or check the length of the properties.
If you do not need the original objects, you could build the result set from the tree.