繁体   English   中英

如何使用“ lowdb”访问嵌套的JSON对象/数组?

[英]How to access nested JSON objects/arrays with 'lowdb'?

我想知道如何使用lowdb语法访问嵌套的JSON数组/对象?

基本上我有这种结构作为lowdb文件:

{
  "57": {
    "hour": [],
    "day": [],
    "week": [],
    "month": []
  },
  "58": {
    "hour": [],
    "day": [],
    "week": [],
    "month": []
  }
}

现在我想动态填充数组,但是我无法将任何值推入...

我的代码:

const low       = require('lowdb');
const FileSync  = require('lowdb/adapters/FileSync')

const adapter   = new FileSync('myFile.json')
const db        = low(adapter);

....

// add new object
db.set("57", { hour: [], day: [], week: [], month: [] }).write();

console.log(db.get('57').value().hour[0]); // prints ofc 'undefined'
console.log(db.get('57').value().hour);   // prints [] which is correct

// both commands are not working  | for test just push a single item
// later the item will be another object 
// db.get('57').value().hour.push('item').write();
// db.get('57').hour.push('item').write();


// if copying first it's working well
var tmp = db.get('57').value().hour;
tmp.push('item');
console.log(tmp); // outputs [ 'item' ]

我感到由于嵌套结构,lowdb无法实现这一点。 如果可能,有人可以告诉我如何吗?

好吧,我以另一种方式帮助了自己。

我的解决方案是,从lowdb获取整个对象并将其复制到局部变量:

let arrayHour   = db.get(item.ITEM_ID).value().hour;
let arrayDay    = db.get(item.ITEM_ID).value().day;
let arrayWeek   = db.get(item.ITEM_ID).value().week;
let arrayMonth  = db.get(item.ITEM_ID).value().month;

然后以我需要的各种方式编辑数据:

// remove obsolete value
if (arrayHour.length >= 6)
  arrayHour.splice(0, 1);

if (arrayDay.length >= 24)
  arrayDay.splice(0, 1);

if (arrayWeek.length >= 7)
  arrayWeek.splice(0, 1);

if (arrayMonth.length >= 30)
  arrayMonth.splice(0, 1);

...

// add new values
arrayHour.push({name: item.NAME_DE, smkurs: item.SMKURS, ts: item.TS});

...

然后将整个集合推回到lowdb

// put the values back
db.get(item.ITEM_ID).push({"hour": arrayHour, "day": arrayDay, "week": arrayWeek, "month": arrayMonth}).write();

这运行良好,并且lowdb不必处理嵌套对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM