1

current code

priceHistory is object which has object.

Object {
  "2020-05-17 10:43:45": Object {
    "created_at": "2020-06-17 10:43:45",
    "price": 1000,
  },
  "2020-05-17 10:43:51": Object {
    "created_at": "2020-07-17 10:43:51",
    "price": 2000,
  },
  "2020-05-17 10:43:56": Object {
    "created_at": "2020-08-17 10:43:56",
    "price": 3000,
  },
  "2020-05-17 10:44:01": Object {
    "created_at": "2020-09-17 10:44:01",
    "price": 4000,
  },
}
Object.keys(priceHistory).forEach((history) => {
  console.log(priceHistory[history]);
});

problem

When using forEach for priceHistory, console.log(priceHistory[history]); outputs

Object {
  "created_at": "2020-07-17 10:43:51",
  "price": 2000,
}
Object {
  "created_at": "2020-08-17 10:43:56",
  "price": 3000,
}
Object {
  "created_at": "2020-09-17 10:44:01",
  "price": 4000,
}
Object {
  "created_at": "2020-06-17 10:43:45",
  "price": 1000,
}

The order of object has been changed. How can you solve this? created_at is string and price is number.

I would appreciate it if you could give me any advices.

LPFJ
  • 187
  • 1
  • 4
  • 13

1 Answers1

0

Here is a solution which avoids using new Date () to perform this sorting

const priceHistory = 
    { "2020-05-17 10:43:45": { "created_at": "2020-06-17 10:43:45", "price": 1000 } 
    , "2020-05-17 10:44:01": { "created_at": "2020-09-17 10:44:01", "price": 4000 } 
    , "2020-05-17 10:43:51": { "created_at": "2020-07-17 10:43:51", "price": 2000 } 
    , "2020-05-17 10:43:56": { "created_at": "2020-08-17 10:43:56", "price": 3000 } 
    } 

Object.keys(priceHistory)
  .sort((a,b)=>a.localeCompare(b))
  .forEach(history=>{
  console.log( JSON.stringify(priceHistory[history]) )
})
E_net4
  • 27,810
  • 13
  • 101
  • 139
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • Thanks, this actually worked! what do you do by ```.sort((a,b)=>a.localeCompare(b))``` ? – LPFJ May 18 '20 at 03:21
  • this is standard JS function to compare strings (based on the idea of your input keys all having the same format) see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare – Mister Jojo May 18 '20 at 03:27