removing a property from an object using AngularJS

Currently, I am working on a project involving AngularJS. The main goal of this project is to create a dynamic JSON generator using AngularJS. I have already developed the initial version and it works well. However, there is a minor issue with my application that needs addressing. Whenever a user enters information, it is automatically added to the object with <> as the key. Even if the user modifies or clears the input form, the key remains in place even when the form is empty. Does anyone have suggestions on how to resolve this particular problem?

Here is the HTML code:

<div ng-controller="ctrl">
    
<form>GivenName:
        <input type="text" ng-model="person.givenName" ng-change='change()'/>
        <br>FamilyName:
        <input type="text" ng-model="person.familyName" ng-change='change()' />
        <br>Gender:
        <input type="text" ng-model="person.gender" ng-change='change()' />
        <br>Nationality:
        <input type="text" ng-model="person.nationality" ng-change='change()' />
        <br>WorksFor:
        <input type="text" ng-model="person.worksFor" ng-change='change()' />
        <br>JobTitle:
        <input type="text" ng-model="person.jobTitle" ng-change='change()' />
        <br>Url:
        <input type="text" ng-model="person.url" ng-change='change()' />
        <br>Image:
        <input type="text" ng-model="person.image" ng-change='change()' />
        <br>
    </form>
     <h1>Your JSON</h1>

    <pre>{{output | json}}</pre>
</div>

And here is my Angular file:

angular.module("watch", [])

.controller("ctrl", function($scope) {
    $scope.output = {
            "@context": {
            "schema": "http://schema.org/"
},
           "@graph": [{
            "@id": "person",
"@type": "schema:Person"
}
]

    }


    $scope.person = {};
   
    function changeKeyValue() {

        for (var key in $scope.person) {
            if ($scope.person.hasOwnProperty(key)) {
                $scope.output["@graph"][0]["schema:" + key] = $scope.person[key];
            }
else if 

        }
    }

    $scope.change = function () {
        changeKeyValue();
    }
})

Answer №1

Ensure to include an if statement within your changeKeyValue function that verifies if the property value is empty. If it is, then proceed to delete the key.

if(!$scope.person[key].length){
    delete $scope.output["@graph"][0]["schema:" + key];
} else {
    $scope.output["@graph"][0]["schema:" + key] = $scope.person[key];
}

Demo

angular.module("watch", [])

.controller("ctrl", function($scope) {
    $scope.output = {
        "@context": {
            "schema": "http://schema.org/"
        },
        "@graph": [{
            "@id": "person",
"@type": "schema:Person",
    }]
    };

    $scope.person = {};
   
function updateData() {

        for (var key in $scope.person) {
            if ($scope.person.hasOwnProperty(key)) {
                if(!$scope.person[key].length){
                   delete $scope.output["@graph"][0]["schema:" + key];
                } else {
                   $scope.output["@graph"][0]["schema:" + key] = $scope.person[key];
                }
            }
        }
    }

    $scope.change = function () {
        updateData();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="watch" ng-controller="ctrl"  >
    
<form>GivenName:
        <input type="text" ng-model="person.givenName" ng-change='change()'/>
        <br/>FamilyName:
        <input type="text" ng-model="person.familyName" ng-change='change()' />
        <br/>Gender:
        <input type="text" ng-model="person.gender" ng-change='updateData()' />
        <br/>Nationality:
        <input type="text" ng-model="person.nationality" ng-change='change()' />
        <br/>WorksFor:
        <input type="text" ng-model="person.worksFor" ng-change='change()' />
        <br/>JobTitle:
        <input type="text" ng-model="person.jobTitle" ng-change='change()' />
        <br/>Url:
        <input type="text" ng-model="person.url" ng-change='change()' />
        <br/>Image:
        <input type="text" ng-model="person.image" ng-change='change()' />
        <br/>
    </form>
     <h1>Your JSON</h1>

    <pre>{{output | json}}</pre>
</div>

Answer №2

To remove a key-value pair in JavaScript, you can use the delete operator. You can learn more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

If you want to create a function called changeKeyValue that performs this action, it should be structured like this:

function changeKeyValue() {
    for (var key in $scope.person) {
        if ($scope.person.hasOwnProperty(key)) {
            if($scope.person[key]) {
                // Update output with new key-value pair
                $scope.output["@graph"][0]["schema:" + key] = $scope.person[key];
            }
            else {
                // Remove key-value pair from output
                delete $scope.output["@graph"][0]["schema:" + key]
            }
        }
    }
}

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

Sending information from AngularJS to nodeJs/Sequelize

I am currently in the process of developing an e-commerce website using Node.js/Sequelize and AngularJS. For my project, I have organized it into 2 main folders: Client (which houses AngularJS starter files) https://i.stack.imgur.com/0vzsF.png Server ...

Tips for implementing a jQuery mouseleave function for multiple div elements sharing the same id

I am facing an issue with my website where multiple divs share the same id. I need to implement a mouseleave function for all of these divs that have this specific id. Within my $(document).ready function, I currently have the following code... $('#m ...

Placing the date of each blog post at the end of the excerpt

Currently, there is a grid section on the homepage of our site showcasing the two most recent blog posts. I am looking for a Javascript solution to relocate the date to the bottom of each block, outside of the border. For reference, you can visit the follo ...

searching backwards using regular expressions

I have successfully extracted <%? imagepath;%> using the following regex from a string. <%(\?|.|\s)*%> <img src="http://abc/xyz/<%? imagepath;%>.gif"> <img not_src="http://abc/xyz/<%? imagepath;%>.gif"> <i ...

"Geolocation within the boundary of a map: what's the message

Can text be placed inside a shape using ng-map? <ng-map default-style="true" zoom="18" center="53.25564575, -113.81401062" map-type-id="SATELLITE"> <shape name="rectangle" editable="true" draggable="true" bounds="[[53.2559199723254, ...

What methods can be used to identify the pattern entered by the user for data types such as `Int`, `VarChar`, `

I have a dropdown menu containing data types. There is also a text box for entering Regex patterns. If "/test/" is entered in the textbox or "Int" is selected from the dropdown, then it's an incorrect pattern. If "/[0-9]/" is entered in the ...

JavaScript classList.remove function experiencing inconsistencies

Take a look at this fiddle: JSFiddle The HTML code: <table class="myTable"> <tr> <th>Some text</th> <td class="align"> <span class=" someStyle">1</span>/<span class="otherStyle">15</span& ...

Exploring the world of npm packages: from publishing to utilizing them

Exploring My Module npmpublicrepo -- package.json -- test.js The contents of package.json are as follows: { "name": "npmpublicrepo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Erro ...

Is it possible to employ a method to eliminate a specific valuable element 'this' from an array?

I am working on a task management app that allows users to create a To-Do list and remove specific items from the list. Currently, I am facing an issue with using 'localStorage' to save the list when the page is refreshed. The problem arises when ...

React app is having issues with Hammer.js when used together with touch emulator on touch devices

I've been experimenting with testing touch events using Hammerjs in React, and I'm facing quite inconsistent behavior across different browsers and events. Consider this basic code snippet: import React from 'react'; import PropTypes ...

Guide to organizing an HTML table column with a header click using PHP and MySQL

I am currently working on a table that displays data from a MySQL database. I would like to implement functionality that allows users to click on certain columns to sort them in ascending or descending order. However, I am unsure of whether to use PHP, H ...

How to store angular 2 table information generated using ngFor

I am currently working on a project where I need to create an editable table using data retrieved from the back end. My goal now is to save any updated data. I attempted to use formControl, but it seems to only save the data in the last column. Below is a ...

Tips for incorporating a loading gif image with infinite scroll functionality in an AngularJS application

Imagine a scenario where there is a large amount of data and we decide to implement infinite scrolling with an infinite-scroll-distance of 2. Every time new data is being loaded, an animated loading gif should be displayed. Is such functionality possible ...

What is the established procedure for resetting all elements within an (X)HTML document?

Is there a way to reset elements without using a form like how it can be done with JavaScript? document.forms[0].reset(); I am utilizing AJAX, so do I need to loop through all the elements using JavaScript? ...

Creating a versatile protractor framework to streamline multiple project implementations

There's a concept in the works for creating a 'protractor core' that will be utilized by various projects for UI testing. Currently, I have an Angular project called 'project1' with e2e tests (cucumber-protractor-typescript) that c ...

Encountering an issue: Unable to initiate a local server when running `npm start`

Currently diving into the world of React, I successfully set up a React app. However, upon running npm install after typing cd davidsapp, I encountered numerous warnings and errors. Subsequently, when issuing the command npm start, all of the errors are di ...

obtaining pictures from information obtained in vuejs

Trying to showcase images in my code that are already stored in my data like this: <div > <tr v-for='(ships,index) in destroyedShipBox' :key='index'> <td>{{ships}}</td> ...

console rendering duplication in React

Why am I seeing duplicate log entries in the console? While working on another project, I noticed that the number of HTML elements being added using jQuery was twice as much as expected (specifically while building a notification framework). To investigate ...

Sketch a straight path starting from the coordinates x,y at a specified angle and length

Is there a way to draw a line in Javascript starting from a specific x/y position with a given length and angle, without having to define two separate points? I have the x/y origin, angle, and length available. The line should be placed on top of a regula ...

Removing an item from an array in Mongoose

I'm encountering an issue with removing an Object from an Array and I'm unsure of the correct way to use $pull for this action. Any help would be greatly appreciated! JSON data "accountId": "62efd8c008f424af397b415d", "l ...