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!

3
  • You just need to map. return {id:x[0],num:x[1],hour:new Date.getHours()}. What you got is a collection. Commented Jul 24, 2014 at 7:41
  • stackoverflow.com/questions/1359761/sorting-a-javascript-object Commented Jul 24, 2014 at 7:42
  • I don't think _.object needs a predicate. as you are trying to give. Commented Jul 24, 2014 at 7:54

1 Answer 1

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()}
            });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.