Dushyant Bangal
Dushyant Bangal

Reputation: 6403

lodash values of single object to array of objects with fixed key

I have an object

{
    key1:'val1',
    key2:'val2',
    key3:'val3',
    key4:'val4'
}

I need to convert it to the following:

[
    {key:'val1'},
    {key:'val2'},
    {key:'val3'},
    {key:'val4'}
]

The key in the final object is fixed.

How do i do this using lodash or underscore? I know I can use _.values and then forEach on it, but somehow that doesn't feel right.

Upvotes: 1

Views: 606

Answers (2)

Season
Season

Reputation: 4366

Below is a lodash version

_.map({
    key1: 'val1',
    key2: 'val2',
    key3: 'val3',
    key4: 'val4'
}, function( value ) { return { key: value }; } );

Upvotes: 0

baao
baao

Reputation: 73231

No need for lodash or underscore. Just map over the Object.keys()

var obj = {
    key1:'val1',
    key2:'val2',
    key3:'val3',
    key4:'val4'
};

var newObj = Object.keys(obj).map(function (k) {
    return {
  	key: obj[k]
    }
});

console.log(newObj);

Upvotes: 1

Related Questions