-2

I have some documents in a Mongodb collection that are of the wrong type, they look like this:

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

returns

{ "_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 } } 
}

The "History" element should be converted to an array, like this:

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

Is this doable with JavaScript?

addition:

I was not be able to isolate the History object or loop through it. I used this code

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 } } }

But always got the entire object and not only the History. Apparently used the wrong syntax as it is :

db.stockData.find( {}, {History:1}).forEach(function(doc) { 
printjson(doc.History);   } );
Non Plus Ultra
  • 867
  • 7
  • 17

3 Answers3

2

If you have to support IE browser too ,you have to use Array#map function.

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);
dganenco
  • 1,596
  • 1
  • 5
  • 16
2

To convert an object with numerical keys to an array, you can use Object.values():

const obj = {"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 result = Object.values(obj.History)

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

yes, it's doable in JavaScript using Object.values()

let obj = db.stockData.find({productcode:"EMIM.AS"},{History:1} )
let result = Object.values(obj.History)

it returns your target array.

hesam rajaei
  • 320
  • 3
  • 8