One thing I am aware of is the ability to define an object reference from a string, such as this:
obj['string']
This essentially translates to obj.string
.
My query arises when trying to extend this beyond the first object value. This is what I would like to achieve:
obj['string1.string2']
Unfortunately, this fails because the key (string1.string2
) does not exist within the object. While I understand how this works, my struggle lies in figuring out how to make it work and return obj.string1.string2
.
The specific scenario that I am dealing with involves an array of objects:
let players = [
{
name: 'Player 1',
points: {
current: 100,
total: 1000
}
},
{
name: 'Player 2',
points: {
current: 50,
total: 500
}
}
];
I am attempting to sort the array based on the current value of points using players.points.current
.
The sorting method I have implemented is as follows:
players.sort((a, b) => { return b.points.current - a.points.current });
While this method works effectively, I am exploring ways to create a function that can accept a 'sorting' term in string format like points.current
or points.total
, aiming to enhance reusability and reduce code repetition. In my efforts to pass the string into the object reference, I encountered the issue where the key does not match any existing values: players['points.current']
I would sincerely appreciate any help or guidance offered by individuals who could assist me in this matter. Should I approach this dilemma from a completely different perspective?