1

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

This is great! Which one do you think is faster / less expensive? The one that @Season posted with lodash or this one?
I didn't check, but I would always prefer build in js functions over a library if they are doing the same with the same (or less) amount of code. @DushyantBangal
Can you help me with this one?: stackoverflow.com/questions/39774303/…
0

Below is a lodash version

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

1 Comment

Can you help me with this one? stackoverflow.com/questions/39774303/…

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.