【问题标题】:Rebuild a JSON doc by Looping over the contents?通过循环内容来重建 JSON 文档?
【发布时间】:2014-02-25 06:25:09
【问题描述】:

我希望 .get 一个 array 的 MongoDB 文档,使用 object.foo 从数组构建 var,然后重新构建所有 foobar 的 array,一旦排名.. em>

有另一个函数来处理一些用于排名的变量计算。

我正在尝试重新构建 JSON 数组,使用 for 循环遍历元素,但是:

..由于某些奇怪的原因,数组以逗号开头

..循环遍历新建的数组似乎循环遍历字符而不是值

控制台记录:[01:10:40.833] ", {title: "Title1", quantity: "2", _id: "530c12c66e6b0de318000001"}, {title: "Title2", quantity: "4", _id: "530c12cc6e6b0de318000002"}, {title: "Title3", quantity: "8", _id: "530c12d16e6b0de318000003"}"

然后控制台记录这个:[01:10:40.833] undefined 213

MongoDB 通过 .get:

function getAll(res) {

    db.collection('demo').find().sort( { value: 1 } ).toArray(function (err, docs) {
        console.log("Got the Docs: " + utils.inspect(docs));

        // each doc looks like: { _id: ObjectID, title: 'string', quantity: int}

        res.json({docs: docs});

    });
}

文档在控制台中如下所示:

[ { _id: 530c12c66e6b0de318000001,
    title: 'Sample1',
    quantity: 2 },
  { action: 'Sample2',
    quantity: 4,
    _id: 530c12cc6e6b0de318000002 },
  { _id: 530c12d16e6b0de318000003,
    action: 'Sample3',
    quantity: 8 } ]

重建数组的Javascript函数:

  function reBuild(returnValue)
  {
    console.log(returnValue);

      var docs = returnValue;
      var returnedValue = [];
      var doc;
      for (var i=0, length=docs.length; i < length; i++){
        doc = docs[i];

        if (returnedValue == [])
        {
            returnedValue = returnedValue + '{' + 'title: "' + doc.title + '", quantity: "' + doc.quantity + '", _id: "' + doc._id + '"}';
        }
        else
        {
            returnedValue = returnedValue + ", " + '{' + 'title: "' + doc.title + '", quantity: "' + doc.quantity + '", _id: "' + doc._id + '"}';
        }

      }

    console.log(returnedValue);

      var newDocs = returnedValue;
      var newDoc;
      for (var i=0, length=newDocs.length; i < length; i++){
        newDoc = newDocs[i];

        console.log(newDoc.title);

      }

  } 

【问题讨论】:

    标签: javascript arrays json mongodb


    【解决方案1】:

    您不能简单地将字符串值分配给数组类型变量。 JavaScript 允许您这样做,因为它是松散类型(或动态类型)的。但如果你认为这是你问题的原因。

    在您的代码中:

    function reBuild(returnValue)
      {
          console.log(returnValue);    
          var docs = returnValue;
          //==> Initializes to a array type i.e. equivalent to var returnedValue = new Array();
          var returnedValue = []; 
          var doc;
          for (var i=0, length=docs.length; i < length; i++){
            doc = docs[i];    
            //==>Its better to use === if you want equality without type coersion. i.e. the values must be equal in type as well.
            if (returnedValue == []){     
            //==>Here you are changing the type of `returnedValue` variable from array to String
    //So this condition start failing from next loop onwards.
                    returnedValue = returnedValue + '{' + 'title: "' + doc.title + '", quantity: "' + doc.quantity + '", _id: "' + doc._id + '"}';
                }
                else{
                    returnedValue = returnedValue + ", " + '{' + 'title: "' + doc.title + '", quantity: "' + doc.quantity + '", _id: "' + doc._id + '"}';
                }    
              }    
              console.log(returnedValue);    
              var newDocs = returnedValue;
              var newDoc;
              for (var i=0, length=newDocs.length; i < length; i++){
                newDoc = newDocs[i];    
                console.log(newDoc.title);    
              }    
          } 
    

    您正在循环中更改变量returnedValue 的类型,并且您正在检查条件if (returnedValue == [])。它会自动变为 false,因为它在第一次迭代中从任何 array 更改为 String 类型。因此,您可以查看的方式是数组函数,例如arrayObject.push('YourValue')

    试试下面的代码:

          for (var i=0; i < docs.length; i++){
            //This builds JSON object out of your string and pushes into your array `returnedValue` 
                    returnedValue.push(JSON.prarse('{' + 'title: "' + docs[i].title + '", quantity: "' + docs[i].quantity + '", _id: "' + docs[i]._id + '"}'));
              }   
    

    键入检查的正确运算符是使用===。所以基本上你的问题的答案太宽泛了但我试图指出一些让你接近解决问题的要点。 快乐编码:)

    【讨论】:

    • arrayObject.push() 就像一个魅力.. 谢谢你,非常感谢你的洞察力!关于为什么下一个 for 循环(newDocs = returnedValue)为每个 console.log(newDoc.title);.. console.log(returnedValue[i]); 返回 undefined 的任何想法在 var newDocs 完美列出所有内容之前
    • 可能是因为没有逗号来分隔每个文档?话虽如此,尝试了 if/else,但从不返回值 === []
    猜你喜欢
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多