Creating a JavaScript Object from two arrays

后端 未结 9 821
北海茫月
北海茫月 2020-11-28 06:17

I have two arrays: newParamArr[i] and paramVal[i].

Example values in the newParamArr[i] array: [\"Name\", \"Age\", \"Ema

相关标签:
9条回答
  • 2020-11-28 07:10

    The following worked for me.

    //test arrays
    var newParamArr = [1, 2, 3, 4, 5];
    var paramVal = ["one", "two", "three", "four", "five"];
    
    //create an empty object to ensure it's the right type.
    var obj = {};
    
    //loop through the arrays using the first one's length since they're the same length
    for(var i = 0; i < newParamArr.length; i++)
    {
        //set the keys and values
        //avoid dot notation for the key in this case
        //use square brackets to set the key to the value of the array element
        obj[newParamArr[i]] = paramVal[i];
    }
    
    console.log(obj);
    
    0 讨论(0)
  • 2020-11-28 07:15

    I know that the question is already a year old, but here is a one-line solution:

    Object.assign( ...newParamArr.map( (v, i) => ( {[v]: paramVal[i]} ) ) );
    
    0 讨论(0)
  • 2020-11-28 07:17

    I needed this in a few places so I made this function...

    function zip(arr1,arr2,out={}){
        arr1.map( (val,idx)=>{ out[val] = arr2[idx]; } );
        return out;
    }
    
    
    console.log( zip( ["a","b","c"], [1,2,3] ) );
    
    > {'a': 1, 'b': 2, 'c': 3} 
    
    0 讨论(0)
提交回复
热议问题