jeudi 26 juin 2014

Given an array of objects how do I sort the objects by a property in depth n[1;2]


Vote count:

0




I have an array of objects that I wish to sort by some grouping property data and a string telling me which property to group by(eg: 'Organization' or 'Organization.Name')


I need to write a function so the resulting data structure looks like this :


Input :



beforeData = [
{'name':'John Doe', 'Id':1, 'Organizations':[{'Id':12, 'LongName': 'Group A'},{'Id':13, 'LongName': 'Group B'}]},
{'name':'FooBar', 'Id':2, 'Organizations':[{'Id':13, 'LongName': 'Group B'},{'Id':13, 'LongName': 'Group C'}]},
{'name':'Kristine Bell', 'Id':3, 'Organizations':[{'Id':12, 'LongName': 'Group A'}]},
{'name':'Adrian P', 'Id':4, 'Organizations':[{'Id':12, 'LongName': 'Group A'}]}
]


Output:



afterData = [
{
'Group': 'Group A',
'entities':[
{'name':'Adrian P', 'Id':4, 'Organizations':[{'Id':12, 'LongName': 'Group A'}]},
{'name':'Kristine Bell', 'Id':3, 'Organizations':[{'Id':12, 'LongName': 'Group A'}]},
{'name':'John Doe', 'Id':1, 'Organizations':[{'Id':12, 'LongName': 'Group A'},{'Id':13, 'LongName': 'Group B'}]}]
},
{
'Group': 'Group B',
'entities':[
{'name':'John Doe', 'Id':1, 'Organizations':[{'Id':12, 'LongName': 'Group A'},{'Id':13, 'LongName': 'Group B'}]},
{'name':'FooBar', 'Id':2, 'Organizations':[{'Id':13, 'LongName': 'Group B'},{'Id':13, 'LongName': 'Group C'}]},]
},
{
'Group': 'Group C',
'entities':[
{'name':'FooBar', 'Id':2, 'Organizations':[{'Id':13, 'LongName': 'Group B'},{'Id':13, 'LongName': 'Group C'}]},]
}
]


How would I go about accomplishing this? My current attempts are extremely bloated and take forever given large sets of data. The kicker in this problem is that the function that solves this issue needs to be able to solve it without knowing beforehand whether the "group by property" is in depth 1 or 2(eg: 'Organization' or 'Organization.LongName').



asked 37 secs ago






Aucun commentaire:

Enregistrer un commentaire