【问题标题】:How to access nested JSON objects/arrays with 'lowdb'?如何使用“lowdb”访问嵌套的 JSON 对象/数组?
【发布时间】:2018-04-05 10:49:34
【问题描述】:

我想知道如何使用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 无法做到这一点。如果可能的话,谁能告诉我怎么做?

【问题讨论】:

    标签: javascript arrays json


    【解决方案1】:

    好的,我以不同的方式帮助自己。

    我的解决方案是,从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 不必处理嵌套对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多