how to merge two arrays (array 1d and array 2d) into a object using lodash

sir air :

I am looking for best ways of doing this. I have two arrays (array 1d and array 2d):

key = [1,2,3];
value = [['a','b','c'], ['d','e','f'], ['g','h','i']]

The end result I want is an array of map:

[{1:a,2:b,3:c},{1:d,2:e,3:f},{1:g,2:h,3:i}]

How do I do it the most efficient/clean way using lodash? Thanks!

Ori Drori :

Map the values array, and use _.zipObject() to combine the with the keys with the keys:

const keys = [1,2,3];
const values = [['a','b','c'], ['d','e','f'], ['g','h','i']]

const result = values.map(v => _.zipObject(keys, v))

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

If you use lodash/fp you can generate a function with _.flow() that curries _.zipObject() with the keys, and passes it to _.map(). Now you can call the function with the values to get an array of objects:

const fn = _.flow(_.zipObject, _.map)

const keys = [1,2,3];
const values = [['a','b','c'], ['d','e','f'], ['g','h','i']]

const result = fn(keys)(values)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=28238&siteId=1