Paweł Baca
Paweł Baca

Reputation: 888

Append row to JSON

How I can append array to my JSON after add row to database

[
  {id: 1, content: "aaaa", date: "2017-12-05T23:00:00.000Z"},
  {id: 2, content: "bbbb", date: "2017-13-05T23:00:00.000Z"},
  {id: 3, content: "cccc", date: "2017-13-05T23:00:00.000Z"},
  {id: 4, content: "dddd", date: "2017-14-05T23:00:00.000Z"},
  {id: 5, content: "eeee", date: "2017-14-05T23:00:00.000Z"},
]

and I add quest in my database with date 2017-13-05T23:00:00.000Z and how I have to show this i view, but I have to add this row to last value with date 2017-13-05T23:00:00.000Z.

Upvotes: 0

Views: 1118

Answers (1)

3Dos
3Dos

Reputation: 3487

If you'd like to keep the array sorted by date, you could use push and then sort the array by date like so:

const array = [
  {id: 1, content: "aaaa", date: "2017-12-05T23:00:00.000Z"},
  {id: 2, content: "bbbb", date: "2017-13-05T23:00:00.000Z"},
  {id: 3, content: "cccc", date: "2017-13-05T23:00:00.000Z"},
  {id: 4, content: "dddd", date: "2017-14-05T23:00:00.000Z"},
  {id: 5, content: "eeee", date: "2017-14-05T23:00:00.000Z"},
]

const rowToInsert = {id: 6, content: "ffff", date: "2017-13-05T23:00:00.000Z"}

array.push(rowToInsert)

array.sort(function (a, b) {
  return a.date > b.date;
})

console.log(array)

Upvotes: 2

Related Questions