how to merge two arrays into a object using lodash

前端 未结 2 1975
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 15:18

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

相关标签:
2条回答
  • 2021-01-06 15:27

    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] };
    });
    
    0 讨论(0)
  • 2021-01-06 15:48

    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>

    0 讨论(0)
提交回复
热议问题