0

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?

T3rr11
  • 57
  • 9

1 Answers1

0

You can chain the properties, as everything inside the quote is considered a single property name string i.e:

object['thing1']['thing2']

If you want to get this to work with a string with an unknown number of property depth, you would loop over each one, hard to explain but as an example:

let obj0 = {
    obj1: {
       obj2: "answer"
  }
}

let string1 = "obj1.obj2"

let strArr = string1.split('.')

let objSearch = obj0;

strArr.forEach(str => {
    objSearch = objSearch[str]
})

console.log(objSearch)

Keep in mind this only works on success cases where the object properties exist, you will want to have some error handling on if objSearch[str] exists etc

AleksW
  • 703
  • 3
  • 12
  • Good answer, though how could this be done. I was thinking potentially using `'string1.string2'.split('.')` which would create an array of strings. Then it'd be a matter of using them inline with the object? Something I could not figure out fully. – T3rr11 Aug 28 '21 at 09:56
  • 1
    Ah if you don't know the length of the string its a bit tougher -- Have just edited the original answer with a small demo :) – AleksW Aug 28 '21 at 10:07
  • That is a very very interesting concept. It works and I can see what it's doing. Very smart. – T3rr11 Aug 28 '21 at 10:11