How can I transform an array of arrays into an object?

Is there a way to convert an array of arrays into a JavaScript object? The condition being that the first element of each internal array becomes a key in the new object, with the following elements as its corresponding values?

If the first element occurs more than once within the internal arrays, can we ensure only one key is created for that element?

For instance:

var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]

The expected result would be:

var obj = {a: ["b", "e"], c: ["d"]}

In this example, even though a appeared twice in arr, only one key a was created in the final object along with key c.

Answer №1

By utilizing the Array.prototype.reduce method, you can achieve this task in the following manner.

var data = [['x', 'y'], ['z', 'w'], ['x', 'v']];

const result = data.reduce((accumulator, current) => {
  accumulator[current[0]] ? accumulator[current[0]].push(current[1]) : accumulator[current[0]] = [current[1]];
  return accumulator;
}, {});
console.log(result);

Answer №2

Here is a different approach:

let newArr = [['x', 'y'], ['z', 'w'], ['q', 'r']]
const newObj = {}
newArr.forEach(([key, value]) => newObj[key] = [...newObj[key] ?? [], value])

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

Validating the Javascript on my report page

I am struggling to implement JavaScript validation for a report on my table. My JavaScript skills are not strong, and although I have server-side validation in place, I need client-side validation as well. The structure of my page is as follows: <tr> ...

The Ajax success or error message is only shown one time

I have successfully created a form using php, ajax, and JavaScript. By implementing ajax, I am able to display error/success messages without redirecting the user to another page. Everything works as expected when I use console.log to showcase these mess ...

The websocket connection to the production host has encountered issues, while it operates smoothly on localhost within Django

I successfully integrated a websocket connection for real-time updates in my Django application. The issue arises when I try to host the application on a public server, as it fails to connect. I am using Daphne server for hosting. Below is a snippet of my ...

What is the significance of employing the `var` keyword in Vue.js?

As I dive into tutorials and browse through code snippets while immersing myself in learning this framework, I've noticed a common trend - the use of var for declarations. This practice seems prevalent across resources, including the official Vue docu ...

Resolving CORS problem: Eliminating the 'Access-Control-Allow-Origin' Response Header in Angular

Recently, the backend API located at has been proxied by an F5 device which automatically includes the CORS header Access-Control-Allow-Origin: * in all responses. However, the GUI code seems to also be adding a CORS header with Access-Control-Allow-Origi ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

Using AFNetworking in Swift is a great way to handle

What is the process of retrieving JSON data using AFNetworking in Swift? Example of AFNetworking code: let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFHTTPResponseSerializer() manager.POST("http://api.address", ...

Having trouble retrieving a remote JSON link from a local HTML file in Google Chrome

Having trouble fetching a JSON from the following link: [https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050]. When accessed through a browser, the JSON is displayed on screen as expected. However, attempting to fetch this link from JavaScrip ...

Steps to develop a collaborative NPM package

I am currently in the process of developing an NPM package using Typescript that contains solely my type interfaces. At the moment, my project has the following folder structure: project │ index.ts │ └───types │ restaurant.ts │ ...

Having trouble executing the typescript build task: Command 'C:Program' is not valid as an internal or external command

I'm currently working on converting typescript code to JavaScript and have been following the steps outlined in the documentation. To automate the compilation of .ts files, I set up a watch task triggered by pressing Ctrl+Shift+B. However, upon runni ...

Assign value to an element in an array using the value from another element

Is it possible in Javascript to set the value of one array element based on another without changing both elements? Specifically, how can I only modify arr[1] while leaving other elements unchanged? arr[0] = {i: 0}; arr[1] = arr[0]; arr[1]['summ&apos ...

Anticipated to provide a result upon completion of the arrow function with consistent-return

exports.create = (req, res) => { if (!req.body.task) { return res.status(400).send({ message: "Task Can't be empty", }); } const task = new Task({ task: req.body.task, }); task.save() .then((data) => { ...

The functionality of event.preventDefault is not working as expected

Using AJAX, I successfully loaded data into a div. <div id="container"> <a class="hello" href="abc.php">hello</a> // content loaded via AJAX <div> Currently, I am trying to implement jQuery: <script type="text/javascript" ch ...

Implementing CSS styles with the className attribute in a Material UI component within a ReactJS application sourced from a dynamic JSON object

I have a dynamic JSON object that includes a button element. I am using createElement and Material UI to display the data from this object. I wanted to add custom CSS styling to the button component using className, but I've been struggling to achiev ...

Exploring the possibilities of web workers through object-oriented JavaScript, integrating ThreeJS and ScrollMagic

Currently, I am working on a personal website that incorporates Three.js and ScrollMagic using OO Javascript. The 3D objects on the site transform as the user scrolls, providing an interactive experience. While everything is functioning correctly, there is ...

How can I dynamically resize a Bubble using CSV data based on the radius specified in a JSON file when a button is clicked?

I've developed a unique World Bubble Map that displays bubbles based on the geolocation of countries, with the size changing according to parameters selected from radio buttons. For example, when population is chosen, the bubble sizes adjust based on ...

The AJAX success callback is malfunctioning

Below is the snippet I'm utilizing to interact with my web API controller titled Owner. However, despite everything appearing correct, the success function isn't triggering. Any suggestions on what might be causing this issue? $.ajax({ ...

Troubleshooting Issue: Minified CSS in Vue.js not displaying correctly when deployed on Azure static website

I have successfully deployed a static vue.js website to Azure at The development build looks great in Chrome and Safari on OS X, and the production build works fine when served from the dist directory. However, the CSS doesn't seem to be rendering c ...

Best Practices for Laravel and Vue Collaboration

Currently, I am in the process of developing a straightforward invoice system using Laravel. In order to facilitate editing, I need to create a view that consists of a table where rows can be dynamically added and removed. I initially considered using jQu ...

What is a clear indication that a <div> is filled with text?

Picture a scenario where a website contains an element that needs to be filled with random text using JavaScript. Once the div is completely filled, it should reset and begin again. It may sound odd, but the question is: how will the JavaScript determine w ...