最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to merge two arrays into a object using lodash - Stack Overflow

programmeradmin3浏览0评论

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!

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!

Share Improve this question asked May 12, 2016 at 23:44 sammiweisammiwei 3,2109 gold badges42 silver badges53 bronze badges 0
Add a ment  | 

2 Answers 2

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

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/lodash/4.16.6/lodash.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论