Obtain all subelements from the entity

In my Vue project, I am attempting to collect and POST some values to the server. However, I am finding the current implementation to be somewhat frustrating.

Within a Vue method, I have a function that POSTs the collected values from the original object:

    var inputValues = {};
    // Retrieve values from all inputs
    for (key in this.entries) {
        var val = this.entries[key].value;

        if (val != undefined) {
            console.log(key, val);
            Vue.set(inputValues, key, val);
        }
    }

    [Here is the AJAX part that sends 'inputValues' to the server - not so relevant]

Below is an overview of the object structure:

entries: {
    something1: {
        options: {
            "option1": "Option 1",
            "option2": "Option 2",
            "option3": "Option 3"
        },
        visible: true,
        value: undefined
    },
    something2: {
        options: {
            "one": "One",
            "two": "Two",
        },
        visible: true,
        value: undefined
    }
}

While this approach 'works', I feel that there could be room for improvement.

Is there a way to fetch all values of this object like this.entries[].value, or should I store the values of the input fields in a separate object? I am unsure of the correct approach to take.

Any insights would be greatly appreciated.

Answer №1

Here is an alternative approach that might be considered slightly more elegant:

let inputValues = Object.entries(this.entries)
   .map(([key, value]) => ([key, value.value]))
   .reduce((result, [key, value]) => {
     if (value !== undefined) {
       result[key] = value;
     }
     return result;
   }, {});

Alternatively, you could go for a less functional solution:

let inputValues = {};

for(const [key, obj] of Object.entries(this.entries)) {
  if(obj.value !== undefined) {
    inputValues[key] = obj.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

Exporting a function from one module does not automatically make it accessible in another module

I'm stuck trying to call the retrieve_endpoints function from cli_config.js. I made sure to add the functions to the module exports and included the require statement in the cli_config file. But for some reason, I can't seem to access the retriev ...

Removing an element from an object using ng-model when its value is empty is a standard practice

Utilizing the $resource service to access and modify resources on my API has been a challenge. An issue arises when the ng-model-bound object's value is set to empty - the bound element is removed from the object. This results in the missing element ...

Building multiple files in React allows developers to divide their code

Can a React/Redux application be split into modules during webpack build? For example, having a set of components for users and another set for invoices. I want webpack to generate users.js and invoices.js that can be imported into index.html. If I make ch ...

Creating a Cancel Button in JSP/HTML/JS/CSS Form: A Step-by-Step Guide

It is necessary to incorporate the functionality of "save" and "cancel" in the JSP code for this particular form. By selecting "save", the data entered into the form will be submitted to its intended destination. Alternatively, choosing "cancel" will dismi ...

Nuxt issue: Vue router push not reflecting query updates

Recently, I encountered an issue with vue-router-query. When using a click event to navigate to the filter page and append the URL query to it, there seems to be a problem with updating the query data dynamically. The function responsible for sending the q ...

Is it possible to modify the name of the router-view in Vue.js?

I am just starting to explore Vue.js and I have a question about using multiple components in a single route with different names. Is it possible to change the name of <router-view name="default"> in the App.vue file to something else? Thank you for ...

Personalized Angular calendar selector

Looking for an Angular datepicker with unique input features such as: Ability to navigate using keyboard (e.g. keydown for previous day, keyup for next day) within the input field itself (not just in the datepicker popup) Autocomplete functionality, for ...

What causes setInterval to create an endless loop when used inside a while loop in JavaScript?

I attempted to initiate a delayed "one" call or a "one or two?" question, but instead of working as expected, the function continued running indefinitely. Surprisingly, everything worked perfectly fine without using setInterval. quester2() function quest ...

When using a callback function to update the state in React, the child component is not refreshing with the most recent properties

Lately, I've come across a peculiar issue involving the React state setter and component re-rendering. In my parent component, I have an object whose value I update using an input field. I then pass this updated state to a child component to display t ...

Managing cookies in PHP and JavaScript can present challenges due to variations in how different browsers

Our website utilizes ExpressionEngine as the CMS and Magento's cart for e-commerce. I am encountering challenges with cookies and their accessibility in various sections. A cookie is used for storing search selections, allowing users to return to our ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...

Utilizing ng-if within ng-repeat for dynamically generated option tags in HTML and AngularJS

I am using AngularJS to create a dropdown menu with select and option tags. The menu is referencing a model and looks like this: <select id="edit-location" class="" ng-model="packageLoc"> <option ng-repeat="x in loc" value="{{ x.locationId }} ...

HTML5 Canvas Border

Hey Everyone, I've been working on an HTML5 canvas project where I set the canvas width to $(window).width(). Everything was going smoothly until I added a border, which caused a horizontal scroll to appear. Important: I attempted to use the innerWid ...

AngularJS filter date is returning a value of NaN-NaN-NaN

I'm facing an issue where the filter I developed is functioning properly on Chrome but not on Firefox. I am puzzled as to why this might be happening. myApp.filter('dateCustom', [ '$filter', function ($filter) { return funct ...

How to set the default value for an angularJS select dropdown

Can someone assist me with setting a default value for a select dropdown using AngularJS? I have explored similar threads on StackOverflow, but none of the suggested solutions have resolved my issue. Therefore, I am reaching out to seek help here. Essenti ...

CORS blocked in the live environment

error + whole page As a newcomer to JavaScript, I recently deployed my project. During development, everything was functioning well. However, I am now facing an issue with CORS when attempting to sign in (registration works without any problems, confirmin ...

Is there a way to stop jQuery dragging functionality from causing the page to scroll unnecessarily

Whenever I drag an element from div1 to div2, the scrollbar in div1 keeps extending until I drop the element in div2. How can I prevent this extension without breaking the element being dragged? <div class="container-fluid"> <div class="row"> ...

Error encountered while trying to update a record using NodeJS, Express, and MySQL modules due to SQL syntax

When attempting to update a MySQL record in NodeJS, I encounter an "app crashed" error in Visual Studio Code's terminal. app2.js: const express = require('express'); const mysql = require('mysql'); // establish connection cons ...

Retrieve the Content-Type header response from the XHR request

My intention is to check the header content type and see if it is text/html or text/xml. If it is text/html, then it indicates an error that I need to address before moving forward. ...

The Javascript calculation function fails to execute proper calculations

I have been facing immense frustration while working on a project lately. The project involves creating a unique Webpage that can calculate the total cost for users based on their selections of radio buttons and check boxes. Assuming that all other functi ...