DEV Community

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

Posted on

3 2

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 !!!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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];
}

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay