2

I want to turn an array such as:

[[0,0], [1, 1], [2, 2]]

into

[{Duration: 0, Title: 0}, {Duration: 1, Title: 1}, {Duration: 2, Title: 2}]

I was thinking of doing something like:

var a = [[0,0], [1, 1], [2, 2]];

_.map(a, function() {return {Duration: , Title: }   });

But I'm not able to reference the current value I'm looping at. What is the simplest way to do this?

2 Answers 2

2

The callback function is given a parameter, the current element (an array here):

_.map(a, function (data) {return {Duration: data[0], Title: data[1]} });

Update: to make dynamic keys

You could do this using the underscore function each, though I'm not really familiar with underscore:

var keys = ['Duration', 'Title'],
    res;

res = _.map(a, function (data, dataIndex) {
    var hashMap = {};

    _.each(keys, function (key, keyIndex) {
        hashMap[key] = data[keyIndex];
    });

    return hashMap;
});
Sign up to request clarification or add additional context in comments.

1 Comment

What if I had an array of values like ['Duration', 'Title', 'etc'], so that I need to set the object values dynamically? Should I place another map within this map? Thanks and I will check this when the time ends.
2

Underscore's map function takes an array and returns a new array. You can map it how you want.

var a = [[0,0], [1, 1], [2, 2]];
var b = _.map(a, function(row) {
  return { "Duration" : row[0], "Title" : row[1] };
})

If you want to do the fields dynamically, you could do this! Javascript is fun.

var a = [[0,0,4], [1, 1, 5], [2, 2, 6]];
var fields = ["Duration","Title","other"];
var b = _.map(a, function(row) {
  return _.object(fields, row);
})

Here is a plunk you can fork to experiment for yourself.

1 Comment

Thanks, I really appreciate it! I will read the code carefully. I upvoted you but will check aduch since he technically answered the question first.

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.