dexie / Dexie.js

A Minimalistic Wrapper for IndexedDB
https://dexie.org
Apache License 2.0
11.62k stars 642 forks source link

how to push to array in a nested object using Dexie? #560

Open akolnati opened 7 years ago

akolnati commented 7 years ago

I am using Dexie IndexedDB wrapper and I am trying to add an object to an existing array which in inside a nested object. The structure looks similar to below

{ 
  Name : 'John',
  age : 33,
  tags : {
     skill: [{
         first: '.NET',
         second: 'JAVA',
         third: [{special1:'sleep'},{special2:'eat'}] 
     }]
  }
}

I have tried many way to push object special3:'run' to skill.third but without success. My last attempt looked something like this

const pathObject = {};
const fullPath = 'result.tags.skill[3].third';
pathObject[fullPath] = {special3:'run'};
db.inspections.update(id, pathObject);

The object is added outside and not inside the array 'third' something like below

{ 
  Name : 'John',
  age : 33,
  tags : {
     skill: [{
         first: '.NET',
         second: 'JAVA',
         third: [{special1:'sleep'},{special2:'eat'}] 
     }]
     skill[3]: {
         third: {special3:'run'}
     }
  }
}

I wish to know if there a way to add to arrays in nested object using Dexie. Help is appreciated.

dfahlander commented 7 years ago

The easiest is to use [Collection.modify()](http://dexie.org/docs/Collection/Collection.modify()) with a callback function to mutate your model:

db.inspections.where('id').equals(id).modify(x => x.tags.skill[0].third.push({special3:'run'}) );

If you want to use a keypath containing array items, it is also possible, as arrays can be looked at as objects with numeric keys:

db.inspections.update(id, {"tags.skill.0.third.3": {special3:'run'}});