Sort objects in array with dynamic nested property keys

  • A+
Category:Languages

I'm trying to sort an array of nested objects. It's working with a static chosen key but I can't figure out how to get it dynamically.

So far I've got this code

sortBy = (isReverse=false) => {     this.setState(prevState => ({         files: prevState.files.sort((a, b) => {             const valueA = (((a || {})['general'] || {})['fileID']) || '';             const valueB = (((b || {})['general'] || {})['fileID']) || '';              if(isReverse) return valueB.localeCompare(valueA);              return valueA.localeCompare(valueB);         })     })); } 

At this point the keys are hardcoded ['general']['orderID'] but I want this part to be dynamic by adding a keys param to the sortBy function:

sortBy = (keys, isReverse=false) => { ... 

keys is an array with the nested keys. For the above example, it will be ['general', 'fileID'].

What are the steps that need to be taken to make this dynamic?

Note: child objects can be undefined therefore I'm using a || {}

Note 2: I'm using es6. No external packages.

 


You can loop ovver the keys to get the values and then compare them like

sortBy = (keys, isReverse=false) => {      this.setState(prevState => ({         files: prevState.files.sort((a, b) => {             const clonedKey = [...keys];             let valueA = a;             let valueB = b             while(clonedKey.length > 0) {                 const key = clonedKey.shift();                 valueA = (valueA || {})[key];                 valueB = (valueB || {})[key];             }             valueA = valueA || '';             valueB = valueB || '';             if(isReverse) return valueB.localeCompare(valueA);              return valueA.localeCompare(valueB);         })     })); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: