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

Testing the onClick event in React components using unit testing

I'm facing an issue with testing a Button wrapper component that utilizes a material-ui button. I tried writing some test code, but it's failing when trying to test the onClick event. index.tsx (ButtonWrapper Component) import React from &ap ...

Move the last specified elements to the beginning of the array

I have an array let colorsArr = ["red", "green", "purple", "pink", "black"]; Is there a way to retrieve a specific number of elements from the END and move them to the BEGINNING of the array? Desired result: example 1: //move last 3 elements let expec ...

Using AngularJS ng-controller within an $http request is causing issues

I have an example of HTML code: <div ng-bind-html="model.main_container"></div> And I am executing something similar in AngularJS: $http.get("/submit", { cache: true }) .success(function(data, status) { if ( status == 200 ) { ...

How to fetch data from DynamoDB using AngularJS

I've been working on retrieving a value from DynamoDB and then assigning that value to ng-model in order to display it. However, I keep running into the issue of the data always being null. DynamoDB table "meta_value": { "clause_note": "Note: go ...

Exploring Material UI: Customizing the styling of components within TablePagination

Is it possible to customize the styling of buttons within the actions panel of the TablePagination component? import { withStyles } from '@material-ui/core'; import MuiTablePagination from '@material-ui/core/TablePagination'; const st ...

Verify the presence of a particular attribute in an HTML tag using Capybara and polling techniques

In my HTML code, the attributes of buttons (such as "AAAAA") will change based on external events. This real-time update is achieved through AJAX pooling. <div class="parent"> <div class="group"><button title="AAAAA"/></div> <di ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

running a prompt command from my PHP/HTML script

I currently run a puppeteer program by typing c:\myProgram>node index.js in the command prompt. However, I would like to automate this process through my PHP program instead of manually entering it each time. Something similar to this pseudo-code ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Issue with Ref when used in a distinct HTML template

I have encountered a frustrating issue with my simple Vue project. When I separate the template and code into individual files, the ref stops working and I end up with an undefined value in the HTML template. This scenario works fine: map.component.vue ...

Exploring how to retrieve the input value from an element with ReactJs

Is there a way to determine if an input field contains a value by referencing another element? Here is my approach: <div className='input-item'> <input ref="accessKey" name="username" className="lci-text" type="text"/> & ...

Using VB.NET to run JavaScript through Selenium's ChromeDriver

I've tried various methods in C# but I can't seem to get them working in VB.NET. It's possible that I'm not initializing it correctly. My goal is to run javascript on a loaded URL using the chromedriver. This is what my code looks like ...

Guide to include particular data from 2 JSON objects into a freshly created JSON object

I have extracted the frequency of countries appearing in an object (displayed at the bottom). The challenge I am facing is that I require geocode information to associate with country names and their frequencies, so that I can accurately plot the results o ...

Easily transfer files without the need to refresh the page by utilizing the power of AJAX

In my page file-upload.jsp, I have the following code snippet: <form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data"> <input type="file" id="upload_file" name="upload_file" multiple="" /> <in ...

Tips for maintaining consistent width of a div:

My current project involves designing a website that displays various quotes, with each quote rotating for a specific amount of time. However, I'm facing an issue where upon loading the page, the first quote triggers the appearance of a scrollbar, mak ...

Utilize fixed values in type declaration

Strange Behavior of Typescript: export type MyType = 0 | 1 | 2; The above code snippet functions correctly. However, the following code snippet encounters an issue: export const ONE = 1; export const TWO = 2; export const THREE = 3; export type MyType = O ...

What is the process for including an additional button in the DateTimePicker feature of material UI?

I'm currently utilizing DateTimePicker in my React application. I wish to incorporate a Clear button positioned to the left of the Cancel Button. import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/pickers"; import DateFnsUtils fro ...

JavaScript application throwing error: "require is not defined"

Currently, I am working on storing an array in a .json file using NodeJS. However, when trying to execute the code below, I encountered an error message saying require is not defined. Can someone provide some guidance on how to resolve this issue? let ans ...

Is it possible to utilize rspec for conducting feature testing on an integrated rails-angular application?

My Rails-Angular application is very basic and integrated. It simply renders a link, fetching data from a GET request to Rails: 'use strict'; angular.module('angularRspec.controllers') .controller('FightersController', ...

Guide on effectively managing props within a single component in React Navigation

When attempting to navigate from my App component to the GamePlay component, I encountered an issue. Here is a snippet of my App.js: import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; imp ...