Guide on setting default attributes for all properties of an object at once

Currently, I'm in the process of developing an AngularJS service provider (function) that achieves the following objectives:

  • Gathers data from multiple tables within an SQLite database
  • Delivers the resulting object to various controller functions

Since the service interacts with different tables having varying columns, the properties of the result object vary based on the source table.

  • Using Object.defineProperties for specific object properties isn't feasible due to the uncertainty of the properties prior to creating the query 'case'
  • One option is to define the object variable properties within the 'switch' statement, although this approach appears messy...

Upon returning the object to the controller functions, certain manipulations are necessary:

  • Ability to override some properties in the returned object (i.e., requiring writable: true)
  • Precisely, employing JSON.parse() followed by overwriting various properties as arrays stored in the SQLite DB are converted using JSON.stringify() before insertion and stored as strings in the DB
  • Encountering complications since the default for the object is writable: false

Inquiry:
How can I establish an object with attributes

configurable: true, writable: true, enumerable: true
for all (future) properties of an object? In other words, how do you set the default attributes for an object without knowing the exact property names of the object beforehand?

Sample code:

this.checkRowExists = function(table, id) {     
    try {
        var deferred = $q.defer();

        switch (table) {
            case "table1" :
                var selectQuery = 'SELECT * FROM ' + table + ' WHERE id=?';
                break;
            case "table2" :
                var selectQuery = 'SELECT * FROM ' + table + ' WHERE id=?';
                break;
            case "table3" :
                var selectQuery = 'SELECT * FROM ' + table + ' WHERE id=?';
                break;
        }

        this.db.transaction(function(tx) {
            tx.executeSql(selectQuery, [id], function(tx, results) {
                    if (results.rows.length > 0){
                        var myRow = {};       // <- How can all properties in the "myRow" object be defined as configurable and writable ??
                        var myRow = results.rows.item(0);
                        deferred.resolve(myRow);  // <- The object "myRow" is then returned to various controller functions
                    } else {
                        deferred.resolve(results.rows.length);
                    }
            }, function(tx, error) {
                    console.log('checkRowExists: Error occurred while searching for profile.', error);
                deferred.reject(error);
            });
        });

        return deferred.promise;

    } catch(exception) {
        console.log('checkRowExists: Error occurred while trying this function.', exception);
    }
};

PS: Although the code functionality is intact, it only returns an object with

writable: false, enumerable: true, configurable: false
, whereas every attribute needs to be set to true

UPDATE:
Despite a partial resolution below, lingering questions persist:
- Why can't a property descriptor be manually altered utilizing the Object.defineProperty method?
- How come enumerable: true when it should default to false? Could this be linked to SQLite db transactions?
- Why aren't the defaults of

writable: false, enumerable: false, configurable: false
being applied to the new object cloned using the JSON methodology?
The solution can be accessed here - contingent on how the object is formed - refer to the commentary below

Answer №1

It appears that one part of the issue is related to how the object myRow inherits the properties and attributes from its original source when copied:

Additionally, it seems impossible to modify these property descriptors directly:
For instance, attempting to use

Object.defineProperty(myRow, "my_property", {configurable: true});
results in a
TypeError: Cannot redefine property: my_property
error.

A POTENTIAL SOLUTION
As suggested in a discussion on Stack Overflow, a practical method for cloning an object involves using this approach:

var newObject = JSON.parse(JSON.stringify(oldObject));

This creates a new object without inheriting the property descriptors from the original object.

Interestingly, this technique produces an object with default descriptors of

writable: true, enumerable: true, configurable: true
(confirmed in Chrome & Safari), which contradicts the default values specified in the specification.

UPDATE:
The discrepancy in property descriptor defaults is due to the object's specific definition - as outlined here. When defined like myObject={}; myObject.a=1;, all descriptors default to true; however, using

Object.defineProperty(myObject, 'a', { value: 1 });
sets any undefined descriptors to false.

The output of the following code snippet reflects this behavior:

// Code snippet here

Remaining queries regarding this solution include:
- What is the performance impact of using

JSON.parse(JSON.stringify(object));
for object copying / cloning?
- Are there any drawbacks to utilizing
JSON.parse(JSON.stringify(object));
for cloning purposes?
(Some limitations are mentioned here, particularly issues with date formats or nested functions within object properties.)

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

AngularJS Mapping between two JSON files

What is the most effective way to map data between 2 JSON files in AngularJS? I need to connect and display information from these files in a table. JSON File 1 [{ "year": 2013, "doctor": "Dr. Smith", "illness": "Flu", "apptdate": " ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

Tips on utilizing React and Node to upload text as a file to Google Drive

Are you wondering how to incorporate React.js as the frontend and Node.js as the backend for uploading/reading files from Google Drive? In my attempts, I've tried writing a string as a text file and then uploading it to Google Drive by following this ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

The type '{}' is lacking the 'submitAction' property, which is necessary according to its type requirements

I'm currently diving into the world of redux forms and typescript, but I've encountered an intriguing error that's been challenging for me to resolve. The specific error message reads as follows: Property 'submitAction' is missing ...

Pass information from a row to an AngularJS controller upon clicking the checkbox within the row

I need help with some HTML code that utilizes AngularJS to display a table. Each row in this table contains a checkbox. Here is a snapshot of the table layout: https://i.sstatic.net/ibDor.jpg Below is the actual HTML code: <div ng-app ng-controll ...

"Utilize AngularJS JavaScript to nest HTML elements within each other for dynamic web

I have developed a unique custom directive called hero. My goal is to set up a nested view for multiple instances of hero. Check out this demo to see it in action. The desired layout looks something like this: <hero a="1"> <hero a="2"> ...

preventing firefox from highlighting text on a webpage

Similar Question: What's the most effective method to prevent text highlighting when clicking inside a div using JavaScript? Is there a way to prevent Firefox from highlighting content when a user clicks and drags? ...

Converting MultiSelect Array from JavaScript to MySQL

I recently implemented a multiselect feature on the client side: <select name="country" data-placeholder="Choose a Country..." tabindex="2"> <option name="country" value="United States">United States</option> & ...

Embed a YouTube video within the product image gallery

Having trouble incorporating a YouTube video into my Product Image Gallery. Currently, the main product photo is a large image with thumbnails that change it. You can see an example on my website here. Whenever I attempt to add a video using the code below ...

Firestore Query sends data object to browser

When making a Firestore query, the browser is displaying [object Object],[object Object] instead of the expected output: router.get('/jobopportunities', async(req, res) => { var jobArray = []; const snapshot = await fireba ...

Issue: Troubleshooting data serialization process using getStaticProps in Next.js

I attempted to retrieve data from an API, but unfortunately encountered the following error: Server Error Error: Issue with serializing .results returned from getServerSideProps in "/". Reason: JSON serialization does not support undefin ...

Animating elements within Firefox can sometimes cause adjacent elements to shift positions

Currently, I am working on a single-page website that utilizes keyboard-controlled scrolling. To achieve the desired scroll effect, I have developed a JavaScript function that animates divs. Here is the JavaScript code: var current_page = "#first"; func ...

Is there a workaround to prevent me from using overflow: scroll when I addEventListener("touchmove", preventBehavior, false)?

I am developing an iOS app using PhoneGap, and I have encountered a problem where the window cannot be moved due to the code document.addEventListener("touchmove", preventBehavior, false); Although this code prevents the window from moving, it also stops ...

Creating an environment variable using the package.json script

I'm trying to set the process.env.ENV variable as either TEST or null using a script in my package.json file. The command below is not working when I run it through package.json (though it works fine when directly executed in cmd). script { "star ...

The re-assignment of `req.session.variable` in Express-session does not carry over between two different routes

I am currently working on a basic app that allows logged in users to search and book train journeys using Express, MongoDB, Mongoose, and Express-session. The selected journeys are temporarily stored in the req.session.order variable (which I believe is gl ...

In C#, transforming JSON serialization to replace single backslashes with double backslashes

When generating JSON to be included directly in an HTML file, it's important to wrap the JSON in a JavaScript string. For example: var dataContacts = '{"Contacts":[{"Id":0,"Active":false,"Company":"Rory The Architect\\, Melt"} ...

JavaScript - Receiving alert - AC_RunActiveContent.js needed for this page to function

When I attempt to open the HTML file in my application, a pop-up message appears stating that "This page requires AC_RunActiveContent.js." However, I have already imported and referenced the AC_RunActiveContent.js file in my package. Can someone assist m ...

Plunker fails to run simple AngularJS demo

I'm having trouble figuring out why this basic example isn't functioning as expected on Plunker. http://plnkr.co/edit/EfNxzzQhAb8xAcFZGKm3?p=preview var app = angular.module("App",[]); var Controller = function($scope){ $scope.message ="Hel ...

I am facing an issue with element.on('submit') not functioning properly within my AngularJS directive

I am having trouble with an ng-submit call that is supposed to trigger a submit event in my custom directive, but for some reason it's not working as expected. Take a look at this plunk to see the issue in action: <div ng-controller="MyCtrl"> ...