how to merge two arrays into a object using lodash

馋奶兔 提交于 2019-12-14 03:39:31

问题


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!


回答1:


I think your question is answered here.

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

const output = _.zipWith(key, value, (key, value)=> ({ 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:


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] };
});


来源:https://stackoverflow.com/questions/37199159/how-to-merge-two-arrays-into-a-object-using-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!