Monday, May 20, 2024
61
rated 0 times [  62] [ 1]  / answers: 1 / hits: 92940  / 8 Years ago, wed, august 24, 2016, 12:00:00

I have two arrays: newParamArr and paramVal.


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


Example values in the paramVal array: [ "Jon", 15, "[email protected]" ].


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": "[email protected]" }.


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


More From » javascript-objects

 Answers
9



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.


[#60930] Monday, August 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidan

Total Points: 72
Total Questions: 95
Total Answers: 121

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
aidan questions
Mon, Oct 11, 21, 00:00, 3 Years ago
Wed, Sep 29, 21, 00:00, 3 Years ago
Sun, Sep 5, 21, 00:00, 3 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;