Encountering a missing value within an array

Within my default JSON file, I have the following structure:

{
    "_name":"__tableframe__top",
    "_use-attribute-sets":"common.border__top",
    "__prefix":"xsl"
}

My goal is to add values by creating an array, but I am encountering an issue where my array returns undefined after pushing the data.

{
    "_name":"__tableframe__top",
    "_use-attribute-sets":"common.border__top",
    "__prefix":"xsl",
    "attribute":[undefined]
}

Initially, I check if the object already contains an array. If not, then I create one. If there's already an array present, no action is taken.

if(!($scope.tObj.stylesheet["attribute-set"][4].attribute instanceof Array)){
        const tableframe__top_content = $scope.tObj.stylesheet["attribute-set"][4].attribute;
        $scope.tObj.stylesheet["attribute-set"][4].attribute = [tableframe__top_content];
 }

Following this, I verify if an attribute with a _name value of something already exists within the array. If it does not, then I proceed with pushing.

var checkTableFrameTopColor = obj => obj._name === 'border-before-color';
var checkTableFrameTopWidth = obj => obj._name === 'border-before-width';

var checkTableFrameTopColor_available = $scope.tObj.stylesheet["attribute-set"][4].attribute.some(checkTableFrameTopColor);

var checkTableFrameTopWidth_available = $scope.tObj.stylesheet["attribute-set"][4].attribute.some(checkTableFrameTopWidth);

if( checkTableFrameTopColor_available === false && checkTableFrameTopWidth_available  === false ){
    $scope.tObj.stylesheet["attribute-set"][4].attribute.push({
            "_name": "border-before-color",
            "__prefix": "xsl",
            "__text": "black"
            },{
            "_name": "border-before-width",
            "__prefix": "xsl",
            "__text": "1pt"
             }
             );
    console.log("pushed successfully");     
    console.log($scope.tObj);       
}

However, I keep getting a null value in the array and encounter an error stating

TypeError: Cannot read property '_name' of undefined at checkTableFrameTopColor
.

What am I doing incorrectly?

EDIT:-

This is the desired outcome that I want to achieve-

{
    "attribute":[
                    {"_name":"font-weight","__prefix":"xsl","__text":"bold"},
                    {"_name":"color","__prefix":"xsl","__text":"black"}
                ],
    "_name":"__tableframe__top",
    "_use-attribute-sets":"common.border__top",
    "__prefix":"xsl"
}

Answer №1

My best guess is to post it as an answer with proper formatting...

Here is the given input:

const input = {
    "_name":"__tableframe__top",
    "_use-attribute-sets":"common.border__top",
    "__prefix":"xsl"
}

Note: The value of input.attribute is undefined.

if(!($scope.tObj.stylesheet["attribute-set"][4].attribute instanceof Array)){
    const tableframe__top_content = $scope.tObj.stylesheet["attribute-set"][4].attribute;
    $scope.tObj.stylesheet["attribute-set"][4].attribute = [tableframe__top_content];
}

So, if you are accessing this input in your if statement:

input.attribute instanceof Array => false

it will return true and execute your code block, defining:

const example.attribute = [input.attribute]
// example.attribute == [undefined]

If I understood correctly, you can resolve this by:

$scope.tObj.stylesheet["attribute-set"][4].attribute = (!tableframe__top_content) 
    ? [] 
    : [tableframe__top_content];

If the attribute value could be falsy, consider checking for undefined or null with `tableframe__top_content === undefined || tableframe__top_content === null`.

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

Modify the background color of one div based on the visibility of another div

My carousel consists of three divs representing a Twitter post, a Facebook post, and a LinkedIn post. These are contained within another div called #social-media-feeds. I am curious if it is feasible to adjust the background color of #social-media-feeds d ...

In JavaScript, private variables are not included in the JSON.stringify output

Imagine creating a class called Rectangle with private fields like width and height, initializing them in the constructor. However, when calling JSON.stringify on an instance of this class, it returns an empty object without including the private members. ...

When processing fails for the term 'for'

Why is the parsing not working as expected? What could be causing an error in this code? This code used to work with a certain JSON format, but after changing the JSON data, the "for" loop has stopped functioning properly do{ let json = ...

How can I pass standard HTML as a component in React?

I need help creating a Higher Order Component (HOC) that accepts a wrapper component, but allows me to pass standard HTML elements as inner content. Here is an example of what I want to achieve: type TextLike = string | {type,content} const TextLikeRender ...

The function to refresh content is causing errors in the code

Creating a comment and replies form where the replies display underneath each comment. I've encountered an issue where I can post replies normally, but when attempting to delete a reply, I must refresh the page. After refreshing, I'm only able to ...

Serializing Form Data with Checkbox Array

I am currently utilizing JQuery to submit a form using the form.serialize method. However, within the same form, there is an array of checkboxes that are dynamically created by a PHP function. Here is the structure of the form: <form class="form" id="f ...

What is the correct way to add a period to the end of a formatted text?

Hello, this marks the beginning of my inquiry. I apologize if it comes across as trivial but I have come across this piece of code: function format(input){ var num = input.value.replace(/\./g,''); if(!isNaN(num)){ num = num.toString ...

Executing a callback function when a window confirmation is triggered during the onbeforeunload event

Currently, I need to implement a feature where a confirmation window pops up when the user tries to close the page. The code snippet for this functionality is included below: window.onbeforeunload=function(){ if(...) { return "Are you sure you want to ...

Updating the index of an array in MongoDB using Node.js proves to be a challenging task

Currently, I am working on creating an API for a bus ticketing system. However, I am facing difficulties in getting it to function properly in Node.js. [ { "id":1, "hour" : "7:30am" , "seats" : [ 0 , 0, 0, 0, 0 , 0, 0, 0, 0 , 0 ...

javascript, contrasting functions and variables

As I delve into the world of Javascript and JQuery (hence why I chose the example below), I have observed an interesting behavior. I noticed that not only can I define a function and call it, but I can also just do something else mysterious by using the do ...

Manipulate the default option in a Select field with JavaScript

I'm currently working on a WordPress post editing page and I need to set up a target link: By default, the option is set to "None", but I want to change it to "Custom Link..." with the following details: <select name="imt_team_href" onchange="imt ...

What is the significance of the source element in Vue3's audio element?

Playing mp3 files works in Vue 2, but not in Vue3. <template> <audio src="../file_example_MP3_700KB.mp3" controls ></audio> </template> In Vue3, the code needs to be modified as follows: <template> <audi ...

Using JavaScript to transfer the data ID from a button to a form

I am working on a project where I have a button that triggers a modal: <button type="button" class="btn btn-primary add-subscription" data-toggle="modal" data-workspace_id="{{ workspace.id }}" data-target="# ...

Vue has issued a warning stating that the type check for the "eventKey" prop has failed. The expected type was a String or Number, but an Array was provided instead. Additionally, it is advised to

The code I am currently using is producing the following errors in the console output: [Vue warn]: Avoid using non-primitive value as key, use string/number value instead. [Vue warn]: Invalid prop: type check failed for prop "eventKey". Expected String, ...

How can we ensure that Ajax consistently provides useful and positive outcomes?

Here is my PHP code: function MailList() { $this->Form['email'] = $_POST["email"]; $index = $this->mgr->getMailList($_POST["email"]); } // SQL code function getMailList($email) { $mailArray = Array(); $sql ...

Empty MongoDB array persists even after POST request

After performing a POST request in Insomnia, my "games" array remains empty. What am I missing? UPDATE: New error after array.push({}) "errorValidationError: games.0.gameID: Path gameID is required., games.0.isGameActivated: Path isGameActivated is requi ...

Changing the decimal point display in AngularJS

When a user enters a number with more than two decimal places in any of the 10 textboxes, I want it to automatically round down to two decimal places. <input ng-model='data.value1' ng-blur="formatDecimals1()"> <input ng-model='data ...

JQuery .click function functioning properly on alternate clicks

Currently, I am integrating JQuery with ReactJS. However, there seems to be an issue where the action that should occur when clicking a button only works on every other click. The first click doesn't trigger anything, but the second one does. I attem ...

Error encountered in the options of the Wordpress theme

While working on creating a custom theme options page for a Wordpress theme, I followed this tutorial: Initially, everything was going smoothly until I integrated the color picker function and script. Subsequently, whenever I tried to access the theme opt ...

The useLocation state is returning as null

I've encountered a debugging issue with my app. It's a straightforward application that fetches random API images from Spoonacular, allowing users to either select "Yah" or "Nah" similar to Tinder. Upon choosing "Yah", the image should be added t ...