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!

0

2 Answers 2

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] };
});
Sign up to request clarification or add additional context in comments.

3 Comments

Where the hell is key coming from?
@elad.chen key is the key (ahem) name as per OP final result he needed.
Here is the link to the lodash zipObject method referenced in the answer: lodash.com/docs#zipObject. Also check out lodash.com/docs#zipObjectDeep for nesting property paths.
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>

2 Comments

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.
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.

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.