DEV Community

Cover image for An object from two arrays
Mitesh Kamat
Mitesh Kamat

Posted on

An object from two arrays

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)

Collapse
 
savagepixie profile image
SavagePixie

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

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

const result = Object.fromEntries(fieldValues.map(addKey))
Collapse
 
miteshkamat27 profile image
Mitesh Kamat

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

Collapse
 
pentacular profile image
pentacular

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

for (let index = 0; index < fieldKeys.length; index++) {
  object[fieldKeys[index]] = fieldValues[index];
}