Utilize JavaScript to transform an array into an object using destructuring

Is there a more efficient method to convert a deconstructed array into an object in JavaScript?

My current approach involves using the axios API library, and when I make multiple queries simultaneously, I receive an array with 4-5 API responses. I then need to transform these responses into an object and pass them to another function. Is there a shorter way to accomplish this task? It's not a major issue, but I have numerous instances of this in my application.

const [foo, bar, baz] = [1, 2, 3]
const obj = { foo, bar, baz }
console.log(obj)
=> {foo: 1, bar: 2, baz: 3}

Answer №1

A handy method called toObj makes use of Object.assign along with map

const toObj = (arr, keys) =>
  Object.assign({}, ...keys.map((key, i) => ({ [key]: arr[i] })));  
  
const arr = [4, 5, 6]
const keys = ['alpha', 'beta', 'gamma'];

console.log(toObj(arr, keys));

Answer №2

Manually declaring the object and props is often the most concise vanilla JavaScript approach. However, if you prefer using libraries, Lodash offers a zipObject method that can achieve the same result in a more streamlined manner, such as:

_.zipObject(['apple', 'banana', 'orange'], [5, 10, 15])

Answer №3

If you're looking for a solution in JavaScript, there isn't a built-in method that fits your exact needs. However, creating a custom function to achieve this is quite simple. Here's an example inspired by _.zipObject from the Lodash library:

function createObject(keys, values) {
  return keys.reduce((object, key, index) => {
    object[key] = values[index];
    return object;
  }, {});
}

console.log(createObject(['one', 'two', 'three'], [1, 2, 3]));

Here's a more concise version as a one-liner:

const createObject = (k, v) => k.reduce((o, c, i)=>(o[c]=v[i],o),{});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to use Python and JavaScript to make a WebElement visible in Selenium

I am currently facing an issue with uploading a PNG file using Selenium. The input element necessary for the upload process is visible to the user but not to Selenium. Following the suggestions in the Selenium FAQ, I tried using JavaScriptExecutor as shown ...

Run the .map() method at regular intervals of 'x' seconds

I have a certain function in mind: function fetchDesign (items) { items.map(item => item.classList.add('selected')) // additional code here } Is there a way to trigger item.classList.add('selected') every 2 seconds, while ensu ...

I am facing an issue with Angular reactive forms where the default values I set in ngOnInIt are not being reflected

Having some issues with setting default values in my Angular app using reactive forms. The defaults I set in ngOnInit are not showing up. I am also using the filter function within the map method. I am trying to select a value based on the URL and have it ...

Is there a way to effortlessly refresh a viewpage with fresh data directly from Firebase?

I am trying to update my HTML page with new data from Firebase in real time without having to refresh the entire page. However, I am facing issues where the view is not updating automatically. How can I achieve this? In my JavaScript file, I query Firebas ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

Promise.all does not wait for the inner Promise.all to complete before continuing

let dataObj = [ { Id: 1, name: 'Alice', Address:[{ city: 'Paris', country: 'France' }] }, { Id: 2, name: 'Bob', Address: [{ city: 'NYC', country: &a ...

Prevent the onClick event in the parent container div from triggering when clicking on a child element

Having trouble with event bubbling and onClick functions within a card element. The card has a heart icon that triggers an onClick function to unlike the card, but it also triggers the onClick function for the entire card which leads to a different page wi ...

Vue Loader: Multiple loaders for a single file extension

Currently, I'm experimenting with incorporating SVG into my vue-loader/webpack template project. I'm in need of loading different types of SVGs: Icons: these are utilized within my components and loaded using svg-inline loader for customizatio ...

What is the best way to create a JSON array in Grails as described below?

Can someone please guide me on how to create a JSON array using Grails? Here is what I have attempted: {"paymentRequestlist":[{"sourceAccountNo":"555555555555555","sourceBankCode":"GLBBNPKA","destinationBankCode":"GLBBNPKA","destinationBankAccountNo":"123 ...

Steps to show a particular row in a Vue.js API

I have a question about how to retrieve data from an API and display it in a textbox when the edit button on a specific row table is clicked. The data should include its own id along with other details. I apologize for sharing my code in this format, as I ...

Populate an ASP Form using Javascript in Android Studio

Being relatively new to Android studio, I have been experimenting with various methods but now need some assistance. I am looking to input data into an ASP.NET Website-form using Android studio. The traditional JavaScript approach does not seem to be effec ...

Utilize a Python script to transmit data to JavaScript through JSON in order to dynamically alter the content of

Currently, I am developing an interactive display that utilizes sensors on a raspberry pi. The display is set to show a webpage and I have implemented a python script to handle sensor interaction. My goal is to change the displayed web page when a user p ...

Retrieve the jquery.data() of an element stored in an HTML file using JavaScript or jQuery

I have a dilemma with storing HTML in a database for later retrieval. Imagine the HTML being a simple div, like this: <div id="mydiv">This is my div</div> To store related information about the div, I use jQuery.data() in this manner ...

Use jQuery to activate the radio button inside a div whenever it is triggered by a change

How can I check which radio button list is clicked and then send a jQuery ajax call for the clicked item? Currently, I have tables with the IDs plan1, plan2, plan3 generated using PHP. Each table has a radio button list. Using jQuery each, how can I achiev ...

Automated system is responsible for flagging and disabling comments

We are facing a puzzling issue at the moment. Our comments form allows users to submit their thoughts on news articles, and each submission is immediately accepted and displayed on the same page. Within each comment, there is a link that enables users to ...

Using AngularJS to pass objects dynamically through ng-include

Below is an example that is fully functional, except for one issue. When using node.title within the HTML code, everything works as expected. However, when trying to use {{node.title}} within the ng-include file, it does not function properly. Only the g ...

Converting a Python List into a PHP array using a MySQL database table

I recently inherited a MySQL database where I encountered an interesting challenge with one of the fields in a table. The field returns a string that was once a Python list, resulting in a format like this: $test = "[u'Person 1', u'Person 2 ...

Effective ways to transmit a variable array from an HTML document to a PHP server

Is there a better method for transferring a variable array from HTML to PHP? I attempted to use the serialize function, but it doesn't seem to be functioning correctly. Any suggestions would be greatly appreciated. //HTML var arrayTextAreasNames = [ ...

What methods can be used to create data for the child component?

Below is the primary code: import {Col,Container,Row} from 'react-bootstrap'; import {useEffect,useState} from "react"; import AppConfig from '../../utils/AppConfig'; import BB from './BB'; import React from "re ...

Separate the iframe sessions

I am working with 6 iframes from the same domain but with different URLs and subdirectories. Each iframe sets a cookie with the same name but a different value using the HTML header "set-cookie". To prevent interference between these cookies, I need to fin ...