-1

Basically I'm trying to copy the first answer on this page (Sorting object properties based on value), and sort my object into an array. But I get this error message:

TypeError: Cannot convert undefined or null to object

What is wrong?

  const denom = {
  'ONE HUNDRED': 100.00,
  'TWENTY' : 20.00,
  'TEN' : 10.00,
  'FIVE': 5.00,
  'ONE' : 1.00,
  'QUARTER': 0.25,
  'DIME': 0.10,
  'NICKEL': 0.05,
  'PENNY': 0.01
  };
  
  const denomSorted = Object.keys(denom[0]).sort((a, b) => denom[0][b] - denom[0][a]);
  
denomSorted.forEach(x => console.log(x + ': ' + denom[0][x]));
  
  
Emilio
  • 1,314
  • 2
  • 15
  • 39

2 Answers2

1

you are missing those [] brackets .

  const denom = [{
  'ONE HUNDRED': 100.00,
  'TWENTY' : 20.00,
  'TEN' : 10.00,
  'FIVE': 5.00,
  'ONE' : 1.00,
  'QUARTER': 0.25,
  'DIME': 0.10,
  'NICKEL': 0.05,
  'PENNY': 0.01
  }];
  
  const denomSorted = Object.keys(denom[0]).sort((a, b) => denom[0][b] - denom[0][a]);
  
denomSorted.forEach(x => console.log(x + ': ' + denom[0][x]));
  
  
Minar Mnr
  • 1,376
  • 1
  • 16
  • 23
1

Cause denom[0] is undefined

Object.keys(denom[0])

will fail. May do Object.keys(denom), and sort after keys:

const denom = {
  'ONE HUNDRED': 100.00,
  'TWENTY' : 20.00,
  'TEN' : 10.00,
  'FIVE': 5.00,
  'ONE' : 1.00,
  'QUARTER': 0.25,
  'DIME': 0.10,
  'NICKEL': 0.05,
  'PENNY': 0.01
  };
  
  const denomSorted = Object.keys(denom).sort((a, b) => a.localeCompare(b));
  
denomSorted.forEach(x => console.log(x + ': ' + denom[x]));

or after values:

    const denom = {      
    'ONE HUNDRED': 100.00,
      'TWENTY' : 20.00,
      'TEN' : 10.00,
      'FIVE': 5.00,
      'ONE' : 1.00,
      'QUARTER': 0.25,
      'DIME': 0.10,
      'NICKEL': 0.05,
      'PENNY': 0.01
      };
      
      const denomSorted = Object.keys(denom).sort((a, b) => denom[a]- denom[b]);
      
    denomSorted.forEach(x => console.log(x + ': ' + denom[x]));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151