DEV Community

Cover image for An object from two arrays

An object from two arrays

miteshkamat27 profile image Mitesh Kamat ・1 min read


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(, index) => ({[key]: fieldValues[index]})))

Here is the complete snippet:

  let fieldValues = ['First Value', 'Second Value', 'Third 
  let result = {};
  const formatKey= (s) => {
    if (typeof s !== 'string') return ''
    return "/" + s.split(" ").join("").charAt(0).toLowerCase() + s.split(" ").join("").slice(1);

  let fieldKeys = => formatKey(item));
  fieldKeys.forEach((key, index) => result[key] = fieldValues[index]);
//output: {/firstValue: "First Value", /secondValue: "Second Value", /thirdValue: "Third Value"}

Hope this helps if you have this kind of usecase.

Cheers !!!

Discussion (3)

savagepixie profile image

You could also use Object.fromEntries to avoid having to use two separate arrays:

const addKey = str => [ formatKey(str), str ]

const result = Object.fromEntries(
miteshkamat27 profile image
Mitesh Kamat Author

Thats great..I should have thought about this. Never mind thanks buddy for this improvisation.

pentacular profile image

Honestly, I feel a simple for loop would be more readable.

for (let index = 0; index < fieldKeys.length; index++) {
  object[fieldKeys[index]] = fieldValues[index];
Forem Open with the Forem app