1

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!

2 Answers 2

6

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>

Sign up to request clarification or add additional context in comments.

Comments

1

A plain Javascript version with Object.fromEntries.

const
    keys = [1, 2, 3],
    values = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']],
    result = values.map(array => Object.fromEntries(keys.map((k, i) => [k, array[i]])));

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.