通过循环内容重建JSON文档?

时间:2014-02-25 06:25:10

标签: javascript arrays json mongodb

我正在寻找。array个MongoDB文档,使用var从数组中构建object.foo,然后重新构建所有的array foob​​ar,曾经排名......

有另一个函数处理一些变量计算以进行排名。

我试图重新构建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);

      }

  } 

1 个答案:

答案 0 :(得分:0)

看到你不能简单地将String值赋给数组类型变量。 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 + '"}'));
          }   

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