Easy method for generating a JavaScript dictionary using an array containing arrays

I have a collection of paired items, and I am looking to convert it into a dictionary.

const collection = [['apple', 3], ['banana', 5]]
const transformed = {'apple': 3, 'banana': 5}

If I were using Python, I could simply do

>>> dict([['apple', 3], ['banana', 5]])
{'apple': 3, 'banana': 5}

What's the most straightforward way (1-line solution) to accomplish this in JavaScript?

Though I initially thought it would take 2 lines of code.

const collection = [['apple', 3], ['banana', 5]]
const transformed = {}
collection.forEach(([key, value]) => transformed[key] = value)

Answer №1

Coming soon:

 const desired = Object.fromEntries(existing);

Expected to debut in ES2019, this feature is gaining traction in various browsers. More info

While waiting for broader support, the current two-line workaround is still recommended.

Answer №2

If you absolutely must condense this into a single line, you can utilize the reduce method.

const initialData = [['a', 1], ['b', 2]];
const finalData = initialData.reduce((obj, [key, value]) => Object.assign(obj, {[key]: value}), {});

However, this approach sacrifices readability and generates temporary objects for each iteration. Personally, I prioritize clarity over attempting to be clever with one-liners.

Answer №3

Implementing Map and Reduce with examples.

If you utilize JSON.stringify(), you may find the application of Reduce beneficial.

// Using Map
const sampleData = [
  ['x', 10],
  ['y', 20]
];
let mappedData = new Map(sampleData);

console.log(mappedData.get('x'));

// Implementing Reduce
mappedData = sampleData.reduce((accumulator, value) => {
  accumulator[value[0]] = value[1];
  return accumulator;
}, {});

console.log(mappedData);

console.log(JSON.stringify(mappedData));

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 automatically adjust select view in AngularJS as model value is updated

My select element is structured as follows: <select data-ng-model="transaction.category" class="form-control" data-ng-options="category.name group by category.parent for category in categories" required> </ ...

Eliminating duplicate entries from a CSV file using Python

I have a CSV file that needs to be transformed into another CSV with a specific format. I am providing the input CSV, the output CSV generated by my code, and the desired output CSV format. Any assistance in achieving this would be greatly appreciated. Inp ...

SequelizeDatabaseError: The operation could not be executed as there is no operator that allows for

I am attempting to create a join between two tables using UUIDs (also have IDs), and the relationships between these tables are quite complex... However, I encounter an error when running the query. The first table is named users, with its UUID labeled a ...

In the realm of asp.net, the OnClick event springs into action after the

My asp button uses OnClientClick to execute a javascript function, and I also want to run OnClick after OnClientClick. However, the OnClick never seems to execute. Despite looking through similar topics on StackOverflow and other websites, I can't see ...

What is the best way to define the active <li> tab using JQuery?

Initially, my HTML code includes a set of <li> elements that I want to dynamically add to the existing <ul>. <ul class="tabs" id="modal_addquestion_ul"> <li class="tab-link current" data-tab="multipleChoice">Multiple Choice< ...

Replacing an array element in React.js

Here is a React.js code snippet where I am trying to utilize an array called distances from the file Constants.js in my Main.js file. Specifically, I want to replace the APT column in the sampleData with a suitable value from the array distances extracted ...

Encountering a problem while retrieving JSON or XML data from a URL using jQuery AJAX

Here is a snippet of code that I've been working on: jQuery(document).ready(function(){ var user_key = "asdflk134"; var app_key = "pigasdb95r91bva"; var params = "app_key="+app_key+"&user_key="+user_key+"&format=xml"; jQuery ...

Strip away styles and scripts from PartialView

Looking to incorporate a Star Rating system using a PartialView named: @{ Html.RenderAction("Rate"); } The goal is to display and manage the star rating code separately from the current page, eliminating the need for the parent .cshtml's CSS and oth ...

Is it possible to bypass the initial bracket when working with arrays in PHP?

I am trying to display the [number] value from each array, but with different parent brackets [], how can I skip the first one and retrieve the desired [number]? Basically, I need to ignore the first set of brackets [] and access the second one containing ...

What steps can I take to ensure that the full tingle modal, which includes an image, is visible when the

Upon loading the page, I noticed that if the browser width is greater than 540px, the modal displaying an image gets cut off (see figure below). What steps should I take to ensure that the vertical scroll bar appears immediately? https://i.sstatic.net/cJv ...

Incorporated React component from Rails-assets.org into a Rails application

I have been trying to incorporate a react component from rails-assets.org into my Rails application. Currently, I am using the react-rails gem to write react view in my application. Now, I want to use other react components such as react-router, react-sel ...

Unable to locate and interact with a concealed item in a dropdown menu using Selenium WebDriver

Snippet: <select class="select2 ddl visible select2-hidden-accessible" data-allow-clear="true" id="Step1Model_CampaignAdditionalDataTypeId" multiple="" name="Step1Model.CampaignAdditionalDataTypeId" tabindex="-1" aria-hidden="true"> <option value ...

Arduino Code - Variable in header file lacking initialization values

Within my Codes.h file, I have the following code that I access through the tab in the Arduino Software. This indicates that the sketch is being properly loaded with the header file. #ifndef __CODES_H__ #define __CODES_H__ PROGMEM prog_uint16_t show_hide ...

What is the best way to transfer a variable from jQuery to a PHP script?

While I am aware that similar questions have been asked in the past, I am facing a unique challenge in trying to create a table with distinct links and pass the id of the link to a PHP page. Here is what I have so far: echo("<p>To reser ...

How can you refresh a single element within an array using Angular.js?

System Background: The application is developed using Angular for the front end with routing capabilities, and Node.js, Express, MongoDB, and Mongoose for the back end. Within a controller, there is an array named $scope.array=[]; that is populated throug ...

Iterating through objects in an array using JavaScript should only happen after the current object

As an illustration: Starting from [x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. x1 compares itself to x0, x2 and x3. And so forth... To [x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. x1 compares itself to x2 and x3 only. x2 only compares ...

What sets this.prototype apart from module.exports?

As a newcomer to the world of Node.js, I am eager to gather information, experiment with testing techniques, and explore the code written by others. In my exploration, I have noticed that creating and requiring modules is a common practice in Node.js. Dif ...

Display a specific number of page indicators on the Flickity plugin

Currently, I am utilizing the flickity plugin to create a slideshow feature on my website. My goal is to display navigation dots on the images to facilitate user interaction. If you are interested, you can access the plugin through this link: I would lik ...

Disabling the loading of JavaScript on a Magento website

Seeking advice - I'm experiencing a delay on my website due to 3 unnecessary javascripts that are being loaded. Is there a way to prevent these scripts from loading or being searched for? Listed below is the website log where I am unable to locate jq ...

What is the best way to transfer an element and all its children to another div without losing any jQuery functionality?

At first, sharing an example of the JavaScript and HTML from my page is challenging because I couldn't make it work on JSfiddle. The issue I'm facing involves jQuery on a page where I've created two tabs. Essentially, it's the same con ...