5

I have an array of objects that looks like so:

var A = [{key:"key1",val:1},{key:"key2",val:2},...,{key:"keyn",val:n}]

And I want to transform A to an object:

{
    key1: 1,
    key2: 2,
    ...
    keyn: n
}

This usecase has never come up, but I was thinking of doing mapKeys and then mapValues and I feel there's a simpler answer. Thanks!

0

5 Answers 5

9

You don't really need lodash to achieve that. Just do this with array.reduce(). See code sample below:

function transformArray(arraySrc){
    return arraySrc.reduce(function(prev, curr){
        prev[curr.key] = curr.val;
        return prev;
    }, {});
}

transformArray([{key:"key1",val:1},{key:"key2",val:2},{key:"key3",val:3}]);
Sign up to request clarification or add additional context in comments.

5 Comments

I'm upvoting your answer because i like using native Array.prototype.reduce but @minitech answered using lodash so i'm accepting his/hers
understood. Thanks for taking the time to explain
Probably should return newObject, or just return arraySrc.reduce(...);. ;-)
@RobG you're correct. I'll be updating the function to return the computed value...
@ShaharZ: You could replace Array.prototype.reduce with _.reduce if you need an Underscore/lodash approach.
4

I'd do this:

var result = _(A).keyBy('key').mapValues('val').value();

Clear and simple.

Comments

4

The best way is to use _.extend.

let list = [{"foo":"bar"},{"baz":"faz"},{"label":"Hello, World!"}];
let singleObject = _.extend.apply({}, list);

Output:

{foo: "bar", baz: "faz", label: "Hello, World!"}

Comments

3

Updating @ry answer to a newer version of lodash:

var result = _.zipObject(
    _.map(A, 'key'),
    _.map(A, 'val')
);

Comments

2

There may be a built-in way that I can’t find, but:

var result = _.zipObject(
    _.pluck(A, 'key'),
    _.pluck(A, 'val')
);

Comments

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.