Dexie : How to add to array in nested object

青春壹個敷衍的年華 提交于 2021-02-08 02:56:49

问题


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 if not is there a way to achieve this using indexeddb. Help is appreciated as problem is been holding back progress


回答1:


The easiest is to use 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'}});


来源:https://stackoverflow.com/questions/44907820/dexie-how-to-add-to-array-in-nested-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!