Converting an array of arrays in JavaScript into an object

Managing a JS array with 66 examples can be overwhelming, but I have narrowed it down to just 4 for simplicity:

[["A","Example1"],["A","Example2"],["B","Example3"],["B","Example4"]]

I am now faced with the challenge of converting this array into an object that will work seamlessly with a multi select drop down menu:

var opt = [{
label: 'A', children:[
        {"label":"Example1","value":"Example1","selected":"TRUE"},
        {"label":"Example2","value":"Example2","selected":"TRUE"} 
      ]
},

{
label: 'B', children:[
  {"label":"Example3","value":"Example3","selected":"TRUE"},
  {"label":"Example4","value":"Example4","selected":"TRUE"}
  ]
}
]

Does anyone know of a more efficient way to accomplish this task?

Answer №1

Update: I have successfully achieved the desired outcome by utilizing the functions reduce() and filter().

const result = [['A', 'Example1'], ['A', 'Example2'], ['B', 'Example3'], ['B', 'Example4']].reduce((acc, cur) => {
  const objFromAccumulator = acc.filter((row) => row.label === cur[0]);
  const newChild = {label: cur[1], value: cur[1], selected: 'TRUE'};
  if (objFromAccumulator.length) {
    objFromAccumulator[0].children.push(newChild);
  } else {
    acc.push({label: cur[0], children: [newChild]});
  }
  return acc;
}, []);

console.log(result);

Answer №2

Here's a snippet that should do the job:

const data = [["A","Example1"],["A","Example2"],["B","Example3"],["B","Example4"]];

const dictionary = new Map();
const result = data.reduce((finalArray, [key, label]) => {
    if (!dictionary.has(key)) {
        const newItem = {
            label: key,
            children: []
        };
        dictionary.set(key, newItem);
        finalArray.push(newItem);
    }
    dictionary.get(key).children.push({
        label,
        value: label,
        selected: "TRUE"
    })
    return finalArray;
}, []);
console.log(result);

Answer №3

Check out this clever and efficient solution that makes use of an object as a map:

const data = [["A","Example1"],["A","Example2"],["B","Example3"],["B","Example4"]];

const opt = data.reduce((results,[key,val]) => {
  if(!results[0][key]) //first element of results is lookup map of other elements
    results.push(results[0][key] = { label: key, children: [] });
  results[0][key].children.push({ label: val, value: val, selected:"TRUE" });
  return results;
}, [{}]).slice(1); //slice off map as it's no longer needed

console.log(opt);

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

Attempting to bring in an image file into a React component

My attempt to add an image at the top of my file failed, so I am looking for help with importing it. The code I originally tried did not work. The image does not display using the code below <img src={require('../../blogPostImages/' + post.bl ...

Assign Multiple Values to a PHP Variable and populate an HTML input field with the value

This is the input field I am currently using. https://i.sstatic.net/0hv1q.jpg Here is how I am displaying/printing my variable. https://i.sstatic.net/3Fptg.jpg I am encountering the following error: Array ( [0] => Notice: Array to string conve ...

Is it considered acceptable to employ an endless loop to continually monitor the connection to a server?

Today marks the beginning of my journey in creating an Angular App. My goal is to establish a connection to a server and display a message on screen if the connection is offline, prompting the user to check their network settings. I currently have a JavaSc ...

Angular array mapping techniques

My JSON Object $scope.selectedItems ={ "RECORDS": [ { "Id": 23040035705987, "arriveddate": "2015/04/24", "expirationDate": null, "replacedDate": null, "processDate": "2015/04/24" ...

launch active link in pop-up dialog

I'm currently working on an Instagram iframe that fetches 9 random images with href links for pictures and spans with the same background. My goal is to display these images in a popup gallery. I've tried using Bootstrap for the popup, but I&apos ...

`Troubleshooting Issue: Autocomplete feature in Jquery Codeigniter not functioning

Having an issue with autocomplete in my codeigniter project. When I input text into the field, a dropdown appears but no values are shown. It looks like this: Screenshot The error displayed in the console is: Screenshoot Below is the relevant code: Mode ...

Tips for achieving a gradual transformation of an element according to the scrolling position

I have been experimenting with using waypoints for two specific purposes. The first objective is to determine whether a user is scrolling up or down and if the container comes into view. However, this functionality is not working as expected. The sec ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

Tips for efficiently rendering large data in nextjs when it comes into view?

Is there a way to create a dropdown option in Nextjs where users can easily select an erc20 token from a token list? I attempted to use a standard mapping function on the token list, but it caused the site to become unresponsive and very slow due to the s ...

How come the button doesn't get enabled after three seconds even though ng-disabled is being used?

index.html <html ng-app='myApp'> <head> <title>TODO supply a title</title> <script src="js/angular.js" type="text/javascript"></script> <script src="js/using built-in directives. ...

Utilize the self-reference feature within styled-components

In my current setup, I have a component structured similarly to the example below. Is there any way for me to reference the Step component itself within the code? Perhaps something along the lines of ${this}? I attempted to use ${Step}, but encountered a ...

Combining a pair of 2D arrays (M and N)

I'm currently tackling a challenge assigned to us first year programming students at university. Question image It has come to my attention that there is a mistake in the question where it mentions (N + K) instead of (M + K) columns. My solution to ...

What is the mechanism behind the functionality of promise chains?

I stumbled upon this code on SO and decided to debug it in order to enhance my understanding of the promise concept. However, I am facing an issue with the code below where the last 'then' function is only fetching the tweet with id=4 instead of ...

Setting up types for variables in Angular 2 componentsHere is an

I have a model that consists of multiple properties, and I aim to set all these properties with a default value of either empty or null. Here is an example of my Model: export class MyModel { name: string; jerseyNumber: number; etc... } In m ...

New issue with Express js 4x: receiving an empty object from :req.params

Having trouble fetching URL parameters in express js as the object is coming back empty. var password= require('./routes/password'); app.use('/reset/:token',password); password.js router.get('/', function(req, res, next) { ...

Tips for generating a random number and verifying if it matches the user input using inner HTML

I'm striving to create something more advanced than what I currently have, but I've hit a roadblock. My goal is to use the method Math.floor(Math.random()*11) to produce a random number. Then, I want to populate the inner HTML of a <p>, alo ...

Avoid matching if a character is found in JavaScript

For my current project, I am attempting to verify if an input field contains a valid "slug." A slug is a string that can only consist of lowercase letters and dashes, typically used in URLs. An issue I encountered is that a user can enter a valid slug ini ...

Error: Can't compile - Accordion controller is necessary

Encountered the following error in the console while using angular-bootstrap ui. My setup includes angular 1.2.6, bootstrap 3.0, and angular-bootstrap 0.10.0. Error: [$compile:ctreq] Controller 'accordion', required by directive 'accordionG ...

How can I convert a PHP array into radio buttons in an HTML form?

I'm looking to develop a survey using HTML, PHP, and Javascript. I have my questions and answers stored in a csv file (which will eventually be transferred to a SQL server). My main concern is how to convert my answers into radio button types so that ...

Creating a leaderboard with the help of arrays

Our teacher assigned us the task of creating a JApplet with a high score feature. The challenge was to utilize an ArrayList containing 10 integer values. Upon pressing a JButton, these values would be shown in a JLabel. Additionally, users could input a n ...