Search code examples
javascriptdexie

Replace values in multiple rows in multiple columns provided a mapped object for each column


In the following table, I need to replace values in name and class columns using the following objects

+----------------+
| id name  class |
+----------------+
| 1   a     x    |
| 2   b     y    |
| 3   a     z    |
+----------------+

name 
{
    a: "John",
    b: "Jill"
}

class
{
    x: "Maths",
    y: "Science",
    z: "Arts"
}

Final table should look like the following:

+----------------------+
|    id name  class    |
+----------------------+
| 1   John     Maths   |
| 2   Jill     Science |
| 3   John     Arts    |
+----------------------+

What's an efficient way to achieve this in dexie.js?


Solution

  • You will need to scan through the entire table and replace rows one by one.

    var map = {
      "name": {
        "a": "John",
        "b": "Jill"
      },
      "class": {
        "x": "Maths",
        "y": "Science",
        "z": "Arts"
      }
    };
    
    var db = new Dexie('yourdbname');
    db.version(1).stores({
      yourTable: 'id'
    });
    
    db.yourTable.toCollection().modify(row => 
      Object.keys(map).forEach(column => row[column] = map[column][row[column]]));