使用lodash组合多个数组

时间:2016-06-14 20:31:37

标签: javascript arrays lodash

我正在尝试搜索一起将阵列组合在一起并使用lodash ex返回一个对象:

var names = ['Franko','Dalia','Peter','Max']
var products = ['Mobile','Tv','Camera']
var result = [{
     'name':'Franko'
     'product':'Mobile'
},{
     'name':'Dalia'
     'product':'Tv'
},{
     'name':'Peter'
     'product':'Camera'
},{
     'name':'Max'
     'product':''
}]

2 个答案:

答案 0 :(得分:1)

几乎与Mike C建议的副本一样,但细节略有不同,请使用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)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.min.js"></script>

答案 1 :(得分:1)

这里有一个简单的纯JS解决方案......

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