react-native-leaderboard
react-native-leaderboard copied to clipboard
How to sortBy on nested object key?
Hi
How do i select a field in sortBy if its nested in an object?
For example:
{username: "alan", id: 123, goalsData: { steps: 10,000, calories: 1,700 } }
what if i want to sortBy 'goalsData.steps' ?
Just to note, i have worked around this by flattening the objects in the array of data that i'm using (response from a fetch call)
Code as follows:
/*Give this function an array of objects and it will merge them into one.*/
var merge = function(objects) {
var out = {};
for (var i = 0; i < objects.length; i++) {
for (var p in objects[i]) {
out[p] = objects[i][p];
}
}
return out;
}
/* Give this function a nested object and it will make it single-level */
var flatten = function(obj, name, stem) {
var out = {};
var newStem = (typeof stem !== 'undefined' && stem !== '') ? stem + '_' + name : name;
if (typeof obj !== 'object') {
out[newStem] = obj;
return out;
}
for (var p in obj) {
var prop = flatten(obj[p], p, newStem);
out = merge([out, prop]);
}
return out;
};
/* Call the flatten function on each object in the fetch call response aray */
const flattenedResponse = response.map(objectItem => flatten(objectItem) )
console.log(flattenedResponse)
this.setState({ leaderboardData : flattenedResponse });`