0

I have 2 arrays -

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

Now in output I want 3 should be key i.e index of [1,2,3,4] and so on

Output should be below -

  selection= = { '3':[1,2,3,4] ,'4':[6,5,4,3] ,'5':[2,9,4]}
Ryad Boubaker
  • 1,491
  • 11
  • 16
Supriya
  • 97
  • 3
  • 11
  • Iterate, get elements at current index from both arrays, add into object. Why you need lodash for that? – Tushar Nov 23 '16 at 13:44

2 Answers2

4

just use _.zipObject https://lodash.com/docs/4.17.2#zipObject

_.zipObject(Numbers, selection)
stasovlas
  • 7,136
  • 2
  • 28
  • 29
  • This answer should clarify that it is using lodash. The only hint is the tag in the question, which is definitely not enough. Likewise, posting just a code snippet cannot possibly qualify as an "answer", even if it is technically correct. – Stephan Bijzitter Nov 23 '16 at 13:54
  • 2
    Despite.. He got the most upvote here, because he is right and because he read the question AND the tag. The answer can be found in lodash documentation, there is nothing to add I think. – Aks Nov 23 '16 at 13:56
3

in plain Javascript, you could iterate numbers and build a new object with a number as key and take as value the item of selection with the same index.

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392