javascriptjavascript-objects

Create an object from an array of keys and an array of values


I have two arrays: newParamArr and paramVal.

Example values in the newParamArr array: [ "Name", "Age", "Email" ].

Example values in the paramVal array: [ "Jon", 15, "jon@gmail.com" ].

I need to create a JavaScript object that places all of the items in the array in the same object. For example { [newParamArr[0]]: paramVal[0], [newParamArr[1]]: paramVal[1], ... }.

In this case, the result should be { Name: "Jon", "Age": 15, "Email": "jon@gmail.com" }.

The lengths of the two arrays are always the same, but the length of arrays can increase or decrease. That means newParamArr.length === paramVal.length will always hold.

None of the below posts could help to answer my question:

Javascript Recursion for creating a JSON object

Recursively looping through an object to build a property list


Solution

  • var keys = ['foo', 'bar', 'baz'];
    var values = [11, 22, 33]
    
    var result = {};
    keys.forEach((key, i) => result[key] = values[i]);
    console.log(result);

    Alternatively, you can use Object.assign

    result = Object.assign(...keys.map((k, i) => ({[k]: values[i]})))
    

    or the object spread syntax (ES2018):

    result = keys.reduce((o, k, i) => ({...o, [k]: values[i]}), {})
    

    or Object.fromEntries (ES2019):

    Object.fromEntries(keys.map((_, i) => [keys[i], values[i]]))
    

    In case you're using lodash, there's _.zipObject exactly for this type of thing.