首页 > 解决方案 > 如何将这些 json 对象转换为正确的数组?

问题描述

我在 Mongodb 集合中有一些类型错误的文档,它们看起来像这样:

> db.stockData.find({productcode:"EMIM.AS"},{History:1} )

返回

{ "_id" : ObjectId("5cb810770720c53598ea2807")
, "History" : {
  "0" : { "year" : 2018, "value" : 22.659 },
  "1" : { "year" : 2017, "value" : 25.11 }, 
  "2" : { "year" : 2016, "value" : 20.82 }, 
  "3" : { "year" : 2015, "value" : 18.49 } } 
}

“历史”元素应转换为数组,如下所示:

"History" : [ 
 { "year" : 2018, "value" : 22.659 }
  ,"year" : 2017, "value" : 25.11 },
 ....
 ] }

这对 JavaScript 可行吗?

添加:

我无法隔离 History 对象或循环遍历它。我用了这段代码

db.stockData.find({productcode:"EMIM.AS"},{History:1} , function( err,doc) { console.log(doc[0].History); });
{ "_id" : ObjectId("5cb810770720c53598ea2807"), "History" : { "0" : { "year" : 2018, "value" : 22.659 }, "1" : { "year" : 2017, "value" : 25.11 }, "2" : { "year" : "2016", "value" : 20.82 }, "3" : { "year" : 2015, "value" : 18.49 } } }

但总是得到整个对象,而不仅仅是历史。显然使用了错误的语法:

db.stockData.find( {}, {History:1}).forEach(function(doc) { 
printjson(doc.History);   } );

标签: javascriptarraysjsonobject

解决方案


如果你也必须支持IE浏览器,你必须使用Array#map函数。

const arr = {
  "History": {
    "0": {
      "year": 2018,
      "value": 22.659
    },
    "1": {
      "year": 2017,
      "value": 25.11
    },
    "2": {
      "year": 2016,
      "value": 20.82
    },
    "3": {
      "year": 2015,
      "value": 18.49
    }
  }
};

const res = Object.keys(arr.History).map(function(key){ 
return arr.History[key]});

console.log(res);


推荐阅读