Sorting Nested JSON Objects with Varying Key Structures in JavaScript - Handling Missing Keys
I'm trying to sort an array of nested JSON objects based on a specific key, but I'm running into problems when some objects don't have that key at all. I'm using JavaScript and the data looks something like this: ```javascript const data = [ { id: 1, info: { name: 'Alice', age: 30 } }, { id: 2, info: { name: 'Bob' } }, { id: 3, info: { name: 'Charlie', age: 25 } }, { id: 4, info: { age: 22 } }, { id: 5, info: { name: 'David', age: 28 } } ]; ``` I want to sort this array by the `age` property within the `info` object. However, since not all objects have the `age` key, I want those objects to appear at the end of the sorted array. Iβve tried a simple sort function, but it throws an behavior when it encounters undefined values: ```javascript const sortedData = data.sort((a, b) => { return a.info.age - b.info.age; }); ``` This results in `TypeError: want to read properties of undefined (reading 'age')`. I attempted to use a ternary operator to handle missing keys, but I need to seem to get the ordering right. Hereβs what I tried: ```javascript const sortedData = data.sort((a, b) => { const ageA = a.info.age !== undefined ? a.info.age : Infinity; const ageB = b.info.age !== undefined ? b.info.age : Infinity; return ageA - ageB; }); ``` This approach works somewhat, but it still doesn't seem to place the objects without an age key at the very end consistently. I need to ensure that all items without an age are sorted to the bottom of the array while still ordering those that do have an age correctly. Any advice on how to resolve this scenario effectively? I'm using Node.js v14.17.0 for this project. Thanks in advance for your help!