使用lodash javascript

时间:2016-11-23 13:43:38

标签: javascript lodash

我有2个数组 -

1 - Numbers = [3,4,5]
   2 - selection= [ [1,2,3,4],[6,5,4,3],[2,9,4]]

现在在输出中我希望3应该是关键,即[1,2,3,4]的索引,依此类推

输出应低于 -

  selection= = { '3':[1,2,3,4] ,'4':[6,5,4,3] ,'5':[2,9,4]}

2 个答案:

答案 0 :(得分:2)

只需使用_.zipObject https://lodash.com/docs/4.17.2#zipObject

_.zipObject(Numbers, selection)

答案 1 :(得分:1)

在普通的Javascript中,您可以迭代numbers并使用数字作为键构建一个新对象,并将具有相同索引的selection项作为值。



var numbers = [3, 4, 5],
    selection = [[1, 2, 3, 4], [6, 5, 4, 3], [2, 9, 4]],
    result = {};

numbers.forEach(function (k, i) {
    result[k] = selection[i];
});

console.log(result);




ES6



var numbers = [3, 4, 5],
    selection = [[1, 2, 3, 4], [6, 5, 4, 3], [2, 9, 4]],
    result = numbers.reduce((r, k, i) => Object.assign(r, { [k]: selection[i] }), {});

console.log(result);