3

I am looking for best ways of doing this. I have two arrays:

key = [1,2,3];
value = ['value1', 'value2', 'value3']

The end result I want is an array of map:

[{key: 1, value: 'value1'} ,{key: 2, value: 'value2'}, {key: 3, value: 'value3'}]

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

sammiwei
  • 3,140
  • 9
  • 41
  • 53

2 Answers2

3

Here's what you need

_.zipObject(key, value);

Actually ... no.

Pure Javascript can though:

var result = key.map(function(val, index){
  return { key: val, value: value[index] };
});
Wainage
  • 4,892
  • 3
  • 12
  • 22
  • Where the hell is key coming from? – elad.chen May 12 '16 at 23:54
  • @elad.chen `key` is the key (ahem) name as per OP final result he needed. – Wainage May 13 '16 at 00:06
  • Here is the link to the lodash zipObject method referenced in the answer: https://lodash.com/docs#zipObject. Also check out https://lodash.com/docs#zipObjectDeep for nesting property paths. – wrj May 13 '16 at 00:52
3

I think your question is answered here.

const key = [1,2,3];
const value = ['value1', 'value2', 'value3']

const output = _.zipObject(key, value);

console.log(output);
/*
[
  {
    "key": 1,
    "value": "value1"
  },
  {
    "key": 2,
    "value": "value2"
  },
  {
    "key": 3,
    "value": "value3"
  }
]
*/
<script src="https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js"></script>
manish
  • 497
  • 9
  • 17
  • 1
    This should be marked as a duplicate (cannot do this until you have 15 rep, I believe). For that reason, this would be best posted as a comment. – Bobby Nov 04 '16 at 22:40
  • Actually, after reading the duplicate, thank heaven this was written by someone who made it so clean and quickly readable. The answer in the link just scrambled my brain. – AndrewBenjamin Oct 26 '17 at 04:57