Introduction
This post is about creating a JavaScript object using two arrays.
I had to create an array of keys with a format: /valueText and values with a format Value text.
So, the resulting object would be:
let result = {
/valueText: 'Value text'
}
So, I wrote a function which would return a key in desired format.
const formatKey= (s) => {
if (typeof s !== 'string') return ''
return "/" + s.split(" ").join("").charAt(0).toLowerCase() + s.split(" ").join("").slice(1);
}
I stored these values in one array which I named fieldKeys.
Now to construct an object from these two arrays, I made use of one array for iteration and kept filling in the object.
There are various methods to do it.
Method 1: **forEach**
fieldKeys.forEach((key, index) => result[key] = fieldValues[index])
Method 2: **reduce**
result = fieldKeys.reduce((acc, key, index) => ({...acc, [key]: fieldValues[index]}), {})
Method 3: **Object.assign**
result = Object.assign(...fieldKeys.map((key, index) => ({[key]: fieldValues[index]})))
Here is the complete snippet:
let fieldValues = ['First Value', 'Second Value', 'Third
Value'];
let result = {};
const formatKey= (s) => {
if (typeof s !== 'string') return ''
return "/" + s.split(" ").join("").charAt(0).toLowerCase() + s.split(" ").join("").slice(1);
}
let fieldKeys = fieldValues.map(item => formatKey(item));
console.log(fieldKeys);
fieldKeys.forEach((key, index) => result[key] = fieldValues[index]);
console.log(result);
//output: {/firstValue: "First Value", /secondValue: "Second Value", /thirdValue: "Third Value"}
Hope this helps if you have this kind of usecase.
Cheers !!!
Top comments (3)
You could also use
Object.fromEntries
to avoid having to use two separate arrays:Thats great..I should have thought about this. Never mind thanks buddy for this improvisation.
Honestly, I feel a simple for loop would be more readable.