1

I have different arrays of same size like this:

var a = ["x", "y", "z"];
var b = [1,2,3];
var c = ["l", "m", "n"];

I want this to convert to an array of object like this:

final_array = [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]

I know I can process the arrays using loops and somehow convert this in above format. What I have tried is this way (since size of all arrays will be same):

var final_array = [];
_.forEach(a, function(value, key){
  var each_list = {};
  each_list.a = a[key];
  each_list.b = b[key];
  each_list.c = c[key];
  final_array[key] = each_list;
})
console.log(final_array); // [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]

But this seems to be a very lengthy way and I am sure there will be some good way to do this using lodash or some other approach.

Can any one please help me with this. I already have searched enough on stack overflow and lodash documentation but could not find a better approach for this.

2 Answers 2

3

This should work:

_.zipWith(a, b, c, function(a, b, c) {
  return { a: a, b: b, c: c };
});

Or, if you can use ES6, this:

_.zipWith(a, b, c, (a, b, c) => ({ a, b, c }) );
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @xs0 this is what I was looking for.
Thanks @undefined for fixing the second example :)
awesome, u made this more beautiful. Thanks
1

In plain ES6, you could use an object with short hand properties and iterate the keys and the the items of the arrays.

var a = ["x", "y", "z"],
    b = [1, 2, 3],
    c = ["l", "m", "n"],
    object = { a, b, c },
    result = Object.keys(object).reduce(function (r, k) {
        object[k].forEach((v, i) => (r[i] = r[i] || {})[k] = v);
        return r;
    }, []);
    
console.log(result);

1 Comment

Thanks @Nina Scholz for your answer. Though it is correct, I was looking for some shortest way to do this, so I have accepted the other answer. Thanks again.

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.