Skip to content Skip to sidebar Skip to footer

Combine Multiple Arrays Using Lodash

I'm trying to search for away to Combine arrays together and returns an object using lodash ex: var names = ['Franko','Dalia','Peter','Max'] var products = ['Mobile','Tv','Camera']

Solution 1:

Almost like the duplicate suggested by Mike C, but with slightly different details, use zipWith:

var names = ['Franko','Dalia','Peter','Max'];
var products = ['Mobile','Tv','Camera'];

var result = _.zipWith(names, products, function(name, product) {
    return {name: name, product: product || ''};
  });

console.log(result)
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.min.js"></script>

Solution 2:

A simple pure JS solution here...

var names = ['Franko','Dalia','Peter','Max'],
 products = ['Mobile','Tv','Camera'],
   zipped = names.map((e,i) =>  ({name: e, product: products[i] || ""}));
console.log(zipped);

Post a Comment for "Combine Multiple Arrays Using Lodash"