I have two arrays: newParamArr[i]
and paramVal[i]
.
Example values in the newParamArr[i]
array:
[\"Name\", \"Age\", \"Ema
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);
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]} ) ) );
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}