2

I need to convert this:

"colors":["pink", "Blue"]

or simply this

["pink", "Blue"]

into this

[{ colors: "pink" }, { colors: "blue" }]

in order to be able to use it in AngularJS. Is there any way to do it using underscore.js? Thanks in advance!

2
  • The use of underscore.js is mandatory? Commented Feb 15, 2016 at 17:44
  • No, I have been trying to do it with underscore.js as I am new in Javascript, but I guess with simple Javascript is OK :) Commented Feb 15, 2016 at 17:45

3 Answers 3

6

Underscore provides the _.map() method, which will allow you to accomplish what you're looking for.

var arr = ['pink','blue'];
var hash = _.map(arr, function(color){ return {colors: color};});

However, undercore's map method is simply a thin wrapper around the native Array#map method in javascript, which can be used as follows:

var arr = ['pink', 'blue'];
var hash = arr.map(function(color){ return {colors: color}; });
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfect. Thank you so much!
2
var newArray = new Array();
colors.forEach(function(item) {
    newArray.push({colors: item});
});

5 Comments

You're not strictly wrong, but it is idiomatic to use map() in this case
I've marked the other one as correct, but many thanks for the help!
@RickyTomatoes it's been a long day, I've corrected the code :)
@Matt although it looks syntactically nicer with map, it is actually equal, if not a little bit faster, in the performance. And the fastest would probably be with a "normal" for loop
@FranePoljak Removing my earlier comment in acknowledgement of the correction. I ran a quick perf test on these cases, forEach came out on top, followed by using a for loop, with map bringing up the rear. The difference, however, wouldn't be noticeable except in extremely demanding performance situations
1

Generally, if you have an object like this:

var obj = {
   key1: ['val1_1', 'val1_2'],
   key2: ['val2_1', 'val2_2']
}

and you want to get something like this:

var arr = [{key1: 'val1_1'}, {key1: 'val1_2'}, {key2: 'val2_1'}, {key2: 'val2_2'}]

out of it.

var arr = Object.keys(obj).map(function(key){
    return obj[key].map(function(item){
        var result = {};
        result[key] = item;
        return result;
    })
}).reduce(function(prevArray, newArray){
   return prevArray.concat(newArray);
}, []);

Or if you want the result to be like:

var arr = [[{key1: 'val1_1'}, {key1: 'val1_2'}], [{key2: 'val2_1'}, {key2: 'val2_2'}]]

just remove the last part (.reduce(...)) which concatenates all arrays.

1 Comment

Thanks, I guess this is a more general case!

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.