Joe82
Joe82

Reputation: 1251

Underscore.js - array to object with same key

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!

Upvotes: 2

Views: 813

Answers (3)

Frane Poljak
Frane Poljak

Reputation: 2365

var newArray = new Array();
colors.forEach(function(item) {
    newArray.push({colors: item});
});

Upvotes: 2

Alireza Mirian
Alireza Mirian

Reputation: 6712

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.

Upvotes: 1

RickyTomatoes
RickyTomatoes

Reputation: 722

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

Upvotes: 6

Related Questions