javascript - 如何将这些 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); } );
解决方案
如果你也必须支持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);
推荐阅读
- regex - VS Code 搜索替换和更改行顺序 Vuejs
- azure - 如何在函数应用中为 Azure SignalR 服务使用不同的连接字符串?
- java - Java:不能从静态上下文引用非静态方法 insertValue(int,java.lang.String)
- react-native - 多个 VirtualizedLists 和 ScrollViews 警告
- django - 在 django 中,我如何通过 url 上传文件?
- java - 使用线性搜索的给定数组中的定点(值等于索引) - 逻辑问题
- ios - 在地图上逐渐将颜色更改为 PIN(标记位置)
- python - Selenium Chrome 无头模式“下载”('chrome://downloads/')页面为空
- javascript - React 钩子不会更新状态和组件
- javascript - 如何遍历数组并根据第一个值创建一个新数组