Transform list of objects into a one-dimensional array

My formData serializeArray function returns an array of objects, such as:

[
        0 : {name: 'animal_monkey', value: 'banana'}
        1 : {name: 'animal_horse', value: 'radishes'}
        2 : {name: 'fruit_banana', value: 'yellow'}
        3 : {name: 'fruit_apple', value: 'red'}
]

I want to organize these elements into a single object based on categories with their values assigned, like this:

{ 
        animal: { 
                        monkey : banana,
                        horse : radishes
                },
        fruit: {
                        banana : yellow,
                        apple : red
               }
}

I attempted this using reduce and Object assign but encountered issues where the values were being overwritten. Here's my attempt:

obj = keys.map((k, i) => k.reduceRight((value, key) => ({[key]: value}), vals[i]) )
result = Object.assign({}, ...obj)

The initial values don't survive the assignment process. Any suggestions on how to achieve the desired outcome?

Thank you!

Answer №1

To separate each name using the underscore character "_", and then form a new object by grouping them into categories and animal names, you can utilize the array#reduce method.

const data = [ {name: 'animal_monkey', value: 'banana'}, {name: 'animal_horse', value: 'radishes'}, {name: 'fruit_banana', value: 'yellow'}, {name: 'fruit_apple', value: 'red'} ],
      result = data.reduce((resultObject, currentItem) => {
            const [category, name] = currentItem.name.split('_');
            resultObject[category] ??= {};
            resultObject[category][name] = currentItem.value;
            return resultObject;
      }, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To create a final combined object, you can initialize a variable and then iterate through each element in the array using the array.forEach method.

let finalObject = {};
arr.forEach(item => {
  let [category, itemName] = item.name.split('_'); // category is everything before '_', itemName is everything after '_'
  finalObject[category] ??= {}; // ensure that the category exists as an object in finalObject
  finalObject[category][itemName] = item.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

Transferring Data from Extension to Webpage for the First Page Load - Firefox

Developing an extension for browsers like Chrome and Firefox. As per our requirements, we need to transfer some stored information from the extension to the webpage during page load. This data should be available on the webpage before any XHR request is tr ...

Analyzing Character Frequencies in a String using C Programming (Error Encountered in my Implementation)

I've been working on a C programming exercise that involves writing a program to count the frequency of each character in a string input. Here is the method I have come up with: void printCharactersFrequenciesOf(char s[]){ size_t stringLength = s ...

The repetition of the react nodejs page load occurs when the get method is utilized

I've successfully set up a page and function for loading the customer list. However, I'm facing an issue where adding the get method to my code results in it being called every time information is received from the URL and the page is rendered. i ...

Maintain the header of a table at the top of the grid as you scroll

Although I know there are multiple ways to write this code, I have attempted (and fixed) it. Since I'm not well-versed in front-end development, I am finding this task to be quite challenging. I discovered that placing the table header within a table ...

Having trouble loading a JSON object into a Datatable using Jquery?

I am currently utilizing DataTables in combination with Jquery. I have a data source in the form of an JSON object that I intend to retrieve via Ajax and showcase within the table. The JSON data is retrieved from the /live/log url and has the following fo ...

Parameter within onClick function that includes a dot

I'm attempting to design a table that enables an onClick function for the Change Password column's items so my system administrator can adjust everyone's password. Each onClick triggers the "ChangePassOpen" function which opens a modal with ...

Ensuring that the text in the Bootstrap navbar is responsive for all screen

Yesterday, I inquired about how to modify my navbar menu to switch from horizontal to vertically arranged depending on layout. However, I've noticed that the responsiveness is not consistent when adjusting the window size. Is there a way to ensure my ...

Whenever an Ajax request is made to a PHP file, it consistently fails to retrieve any data despite the fact that the

Whenever I try to call a basic PHP page using AJAX, the response is always empty, even though the PHP code itself is functioning correctly. If you visit the URL of the PHP file directly, it echoes "Hello World" as expected. But when accessed from JavaScrip ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...

What is the method to selectively disable validation for a certain key within an object in the Joi Schema?

I am currently implementing Joi for validating JSON schemas, and I am in need of removing validation for a specific key (id) within a basic object in the main schema. Here is an example of the schema I am working with: const schema = Joi.object({ id: Jo ...

Sending a message to a specific client using socket.io

Currently delving into socket.io + node.js, I have mastered sending messages locally and broadcasting using the socket.broadcast.emit() function - where all connected clients receive the message. My next challenge is figuring out how to send a private mes ...

Creating a Vibrant Progress Bar with Multiple Colors: A Step-by-Step Guide

I'm still getting the hang of things, so I apologize if my question isn't perfectly clear. What I'm trying to do is create a dynamic progress bar with multiple colors that animates upon loading the page. I've seen some examples similar ...

Collecting information from websites by changing JavaScript parameters

I am currently attempting to extract intraday prices for a specific company from the website Enel Intraday. The issue I am facing is that when the data is fetched, it is spread across hundreds of pages, making it extremely time-consuming to gather all the ...

Having trouble setting up jQuery UI Datepicker in my system

I am attempting to add a datepicker to my website, but it is not showing up in the browser. Could there be an issue with some of the other script files I have? Below is where my datepicker div is located: <body> <!-- Preloader --> <div id= ...

Declare a constant character array pointer

I am currently working on a C++17 project that requires the use of a C-legacy-library. In order to do this, I need to create a const char* array in C-style, but have been struggling with the initialization process. Here is an example below: #include <i ...

Boundaries on Maps: A guide to verifying addresses within a boundary

User provides address on the website. If the address falls within the defined boundary, it is marked as "Eligible". If outside the boundary, labeled as "Ineligible". Are there any existing widgets or code snippets available to achieve this functio ...

Exploring Angularjs: Retrieving the value of a selected optgroup

When using my application, I need to extract the selected optgroup value from a dropdown menu. Here is the sample code: HTML: <select ng-model='theModel' ng-change="display(theModel)" > <optgroup ng-repeat='group in collectio ...

"Exploring the World of Android WebView with JavaScript

My app has a minimum API of 16, and I need to run some javascript on a web view. However, when I try to use mWebView.evaluateJavascript("(function()...)"); I receive a compile error indicating that this feature is only available in API 19 and higher. Ho ...

Determine the bounding box based on the specified distance in miles and the latitude and longitude coordinates provided

I am in need of a solution to calculate the Bounding Box for a given latitude, longitude, and distance. The distance can be in Miles, meters, or feet. While I have come across many articles on how to calculate the Bounding Box in kilometers, I have not be ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...