Dushyant Bangal Dushyant Bangal - 2 months ago 15
Node.js Question

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.

Answer

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