【问题标题】:trying to convetr json array to multiple json objects in nodejs试图将json数组转换为节点js中的多个json对象
【发布时间】:2019-05-08 23:12:12
【问题描述】:

试图将 json 数组转换为 nodejs 中的多个 json 对象,在这里寻求帮助是我的代码尝试循环来实现,但失败只是想将数据作为多个对象而不是数组发送

router.get('/frontpage-mobile', function (req, res, next) {

    qryFilter = { "Product_Group": 'SIMPLE' };

    // if we have a cart, pass it - otherwise, pass an empty object
    var successMsg = req.flash('success')[0];
    var errorMsg = req.flash('error')[0];


    Product.find(qryFilter, function (err, product) {
        // console.log("Product: " + JSON.stringify(product));
        var pro=JSON.stringify(product)
        if (err || product === 'undefined' || product == null) {
            // replace with err handling
            var errorMsg = req.flash('error', 'unable to find product');
            res.send(errorMsg);
        }

        if (!product) {
            req.flash('error', 'Product is not found.');
            res.send('error', 'Product is not found.');
        }
   for(i=0;i<pro.length;i++)
        res.send(pro[i]);
    });
});

【问题讨论】:

    标签: arrays node.js json loops


    【解决方案1】:

    // 虚拟 Mongodb 结果数组 var db_result = [{_id:1,name:"Cake_1"},{_id:2,name:"Cake_2"},{_id:3,name:"Cake_3"}]

    // define data variable 
    var data = { total : 0, dataObj : {} } // default total = 0,  = {}
    var dataObj = {}
    
    // convert array to obj
    // { key1 : obj1, key2 : obj2, key3 : obj3, ... }
    for(var i=0; i < db_result.length;i++){
        let key = "key"+i;
        dataObj[key] = db_result[i];
    }
    
    // assign data to variable 
    data.total = db_result.length;
    data.dataObj = dataObj
    
    // rend back to client
    res.send(data);
    
    
    // Result 
    { 
        "total":3,
        "dataObj":{
            "key0":{"_id":1,"name":"Cake_1"},
            "key1":{"_id":2,"name":"Cake_2"},
            "key2":{"_id":3,"name":"Cake_3"}
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 2016-02-18
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多