I am aware that you can define an object reference from string like this;
obj['string']
Which basically translates to obj.string
My question is how would one extend this past the first object value? This is what I would like to pass.
obj['string1.string2']
Which fails due to that key (string1.string2
) not existing within the object. I understand how this works but what I am failing to figure out is how could one get this to work and return obj.string1.string2
My use case is that I have an array of objects;
let players = [
{
name: 'Player 1',
points: {
current: 100,
total: 1000
}
},
{
name: 'Player 2',
points: {
current: 50,
total: 500
}
}
];
What I am trying to do sort the array based on the current value of points. players.points.current
The sorting method I am using is players.sort((a, b) => { return b.points.current - a.points.current });
Which works great, but in order to create a method that can take a 'sorting' string term like points.current
or points.total
in order to minimise code and make the function more reusable, I was trying to pass the string into the object reference which does not work for obvious reasons as mentioned before that the key does not exist. players['points.current']
Would thank anyone kindly if they could help me. Should I tackle this problem in a completely different way?