0

I have an array like

var myArray = [
  [ '12345678912312', '982322' ],
  [ '98789213123123', '443434' ],
  [ '34534565465645', '387423' ],
  [ '67898798799299', '345334' ],
  [ '09324242342342', '234232' ],
]; 

which I want to convert into an Array of object, something like:

var myObject = [
  {
    id: '12345678912312',
    num: '982322',
    hour: new Date.getHours(),
  },
  {
    id: '98789213123123',
    num: '443434',
    hour: new Date.getHours(),
  },
  {
    id: '34534565465645',
    num: '387423',
    hour: new Date.getHours(),
  },
  {
    id: '67898798799299',
    num: '345334',
    hour: new Date.getHours(),
  },
  {
    id: '09324242342342',
    num: '234232',
    hour: new Date.getHours(),
  },
];

I am using Underscore currently and wondering how (and if) I can use _.object and/or _.map to achieve something like this.

I will also like it to be return-able thing. Like:

var newVar = _.object(_.map(myArray), function(k, v) {
  // Do something
});

Thank you!

J D
  • 1,768
  • 2
  • 18
  • 20

1 Answers1

6

If I understood what you want, This can be done with simple javascript native map

var myObj = myArray.map(function(el){
            return {id:el[0],num:el[1],hour:new Date().getHours()}
            });
Mritunjay
  • 25,338
  • 7
  • 55
  • 68