Search code examples
javascriptindexeddbdexie

Dexie: How to get only one column in the result by column key? (simple array of values insted of objects)


I have this fetch query

await useDatabase.data.where("ts").between(ms - 1000, ms).toArray();

I get the result properly but as an object of data.

[
    {
        "ts": 60.1875,
        "sample": 0,
        "id": 1
    }, 
    {
        ...
    },
    {
        ...
    },
]

is it possible to minimise the size of the result by choosing a single column instead of getting a whole object result of a row? (for sample)

[0,...]

didn't find anything in docs. maybe i'm missing it or using the wrong search keywords.


Solution

  • Not unless you have a compound index of the queried column along with the other column you'd like to return.

    const useDatabase = new Dexie('myDatabase');
    useDatabase.version(2).stores({
      data: 'id, [ts+sample]'
    ]);
    
    await useDatabase.data.where("[ts+sample]").between(
      [ms - 1000, Dexie.minKey],
      [ms, Dexie.maxKey]
    ).keys();
    
    

    This will give an array of [ms, sample] tuples only.

    [
        [60.1875, 0], 
        ...
    ]
    

    You could map it to only get the 'sample' prop:

    result.map(([ts, sample]) => sample)
    

    But if performance is of no concert, you could always do this from the original request (without adding the index):

    result.map(({sample}) => sample)