convert different arrays to array of object using lodash or vanila js

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.

Answers:

Answer

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.