"Converting a text into a property that can be

In my scenario, I have a set of fixed options along with a dynamic number of yes/no radio inputs named other[index]. By utilizing $(form).serializeArray(), I can obtain an array of name/value objects. Through the use of the reduce method, I am then able to condense them into a single object.

const serializedForm = $(event.currentTarget.form).serializeArray();

const gdpr = serializedForm.reduce((aggregation, option) => {
    return {
        ...aggregation,
        [option.name]: option.value === 'true'
    }
}, {});

The issue lies in the result not aligning with my desired outcome:

{
  "canNotify":true,
  "canContact":true,
  "canProcess":true,
  "other[0]":false,
  "other[1]":true,
  "other[2]":false
}

What I actually desire is:

{
  "canNotify":true,
  "canContact":true,
  "canProcess":true,
  "other": [
      false,
      true,
      false
  ]
}

Do you have any recommendations on achieving this structure?

Answer №1

To modify each name, remove the brackets. If the key is already in the array, combine the values into an array using array spread:

const data = [{"name":"canNotify","value":"true"},{"name":"canContact","value":"true"},{"name":"canProcess","value":"false"},{"name":"other[0]","value":"false"},{"name":"other[1]","value":"true"},{"name":"other[2]","value":"false"}];

const updatedData = data.reduce((aggragation, { name, value }) => {
  const isArray = name.includes('[');
  const key = name.replace(/\[.+\]/g, '');
  const val = value === 'true';

  return {
    ...aggragation,
    [key]: isArray ? [...aggragation[key] || [], val] : val
  };
}, {});

console.log(updatedData);

Answer №2

When considering the object structure as a whole, one approach could be to analyze the content of the name before proceeding with the return. For instance, if the name includes the array syntax [] or the word other, we might infer that it belongs to a different type within the form collection structure?

const serializedForm = $(event.currentTarget.form).serializeArray();

const gdpr = serializedForm.reduce((aggregation, option) => {
    if (isInArrayOfOptions(option)) {
        return {
            ...aggregation,
            /* Merge current and next option.value into a new array */
            'other': [...aggregation.other, ...[option.value === 'true']]
        }
    }
    return {
        ...aggregation,
        [option.name]: option.value === 'true'
    }
}, {});

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

(Definition) What is the proper way to reference a variable inside another variable?

Currently, my project is using inconsistent terminology when referring to variables, and I need to clarify this issue. Let's take an object defined in this way: var anObject = { a: { value1: 1337, value2: 69, value3: "420 ...

Creating a search-enabled multi-select feature in a Tabulator.js column

Currently, I am working on a project involving Tabulator.js and attempting to incorporate a column with a multi-select feature that includes a search option. My approach has been to utilize the Select2 library, but I have run into some challenges. Here is ...

Create a social chat platform similar to Facebook by implementing a chat box feature with the help of AJAX, jQuery

Currently, I have developed a chat box with two persistent issues. Despite my attempts to rectify them, I am unable to find a solution. Below, I will outline my code, focusing on the HTML section where the chat box, chat text area, and chat members are dis ...

Spin a Material UI LinearProgress

I'm attempting to create a graph chart using Material UI with the LinearProgress component and adding some custom styling. My goal is to rotate it by 90deg. const BorderLinearProgressBottom = withStyles((theme) => ({ root: { height: 50, b ...

The delivery person is not receiving a reply after making the delivery

When using Express/Node and Postgres with the 'pg' package, the following code snippet is used: const createEvent = (request, response) => { console.log(request.body); const { type, location, current_attendees ...

"Trouble arises with the match() function in relation to email regex validation

After retrieving the HTML content from a website with my function, I am using String.prototype.match along with a regex rule to extract email addresses from that page. However, the issue is that I am receiving a line that matches the regex but does not con ...

Issue encountered with SQL server 2008 due to connection error

My current struggle lies in the connection I am attempting to establish with SQL Server. Unfortunately, whenever I try pressing the period key or entering the server name, I encounter difficulty connecting to SQL Server. ...

Tips for effectively refining an Angular model (array) without compromising its integrity

I am currently working with a model for my view. This model consists of an array of objects: var arr = { "12345qwery": { prop1: "value", prop2: "value" } } // consisting of 500 items When filtering this array today, I use the following method: arr = $ ...

Discovering intersections between Polylines on Google Maps - a comprehensive guide

I'm currently developing a project involving a unique twist on Google Maps, focusing exclusively on natural hiking paths. My routes are built using GPX files converted into Google Maps polylines. Is there an efficient way to identify the intersection ...

What is the reason that the 400 status code consistently causes the enter catch block to execute when using axios?

In the frontend of my website, there is a contact form with three fields -> name, email, message. These fields are then sent to the backend using Axios. If a user fails to fill out any of the required fields, they should see a message saying "please f ...

The MySQL error wreaks havoc on the Node.js server, causing it to

Whenever there is an error or exception coming from MySQL, my nodejs server ends up crashing. This is the code snippet from my backend where I tried using if-else in the query function to handle the response, but it still crashes the server. Even with try ...

MongoDB date query with $gte and $le operators mm/dd/yy

Apologies in advance for any language errors. The problem I am dealing with involves a column in the database called "Date" inside the "startOn" Object. This setup creates a structure like "startOn.Date" with data format as yyyy/dd/mm. For example, if we ...

React Material-ui Dropdown Component

Once I completed my application, I decided to enhance its appearance using Material UI. During the transition from HTML to Material UI, a warning started appearing when selecting an item: index.js:1 Warning: findDOMNode is deprecated in StrictMode. findDO ...

I'm looking to generate a semicircle progress bar using jQuery, any suggestions on how

Hi there! I'm looking to create a unique half circle design similar to the one showcased in this fiddle. Additionally, I want the progress bar to be displayed in a vibrant green color. I've recently started learning about Jquery and would apprec ...

Is it possible for a button to simultaneously redirect and execute a function using asynchronous JavaScript?

After browsing through several related posts, I realized that most of them were using href to redirect to a completely new webpage. However, in my JavaScript code, I have a button that utilizes the Material-UI <Link>. <Button component={Link} to= ...

Ways to transfer a jQuery variable value to a PHP variable

I am trying to transfer a jQuery variable value to a PHP variable on the same page using AJAX in my JavaScript code. I have attempted to print the PHP variable but encountered an error. Any assistance would be greatly appreciated. <script type="text/ ...

Vue.js compatibility issue with SelectBoxIt jq plugin causing malfunction

On a page with numerous dynamically generated select boxes, I am looking to incorporate the jQuery selectBoxIt plugin from . Using Vue js, where is the best placement for the following code snippet to connect the plugin with the select elements? $('. ...

What could be the reason for the GET request not functioning properly in Node.js?

const express = require('express'); const mongoose = require ("mongoose"); const app = express(); const Student = require('../models/students'); require('dotenv').config(); const PORT = process.env.PORT || 3000; const co ...

Determination of Array Size using Powershell

Having some trouble error trapping an empty array in the code below. Any suggestions on how to correct the syntax? $inputstring = "MyOtherFile.rdl" "MyFile.rdl" $cleanstring = $inputstring.replace(""" """,";") $filearray = $inputstring.split(";") if ( ...

Searching in the Kendo Dropdown List using text and value

$(document).ready(function() { $("#selection").kendoDropDownList({ filter: "startswith", dataTextField: "SelectionName", dataValueField: "SelectionID", dataSour ...