I have this function in which I want to access nested attributes from passed arguments inside the function.
var objectsArr = [
{nestedobj:{property:'1'}},
{nestedobj:{property:'3'}},
{nestedobj:{property:'2'}},
{nestedobj:{property:'4'}}
];
function sortObjectsArr(objectsArray) {
if (arguments.length == 2) {
objectsArray.sort((a,b) => a[arguments[1]] - b[arguments[1]]);
}
if (arguments.length == 3) {
objectsArray.sort((a,b) => a[arguments[1]][arguments[2]] - b[arguments[1]][arguments[2]]);
}
if (arguments.length == 4) {
objectsArray.sort((a,b) => a[arguments[1]][arguments[2]][arguments[3]] - b[arguments[1]][arguments[2]][arguments[3]]);
}
//and so on and so forth
}
sortObjectsArr(objectsArr, 'nestedobj', 'property');
console.log(objectsArr);
Is there a nicer way to access the attributes from the object? rather than [arguments[1]][arguments[2]][arguments[3]].... ?