What is the best way to generate an empty object that mimics the structure of an object within an array of objects in AngularJS

I am facing a scenario where I have an array of objects structured like this:

$scope.users = [
    {
        ID: "1",
        Name: "Hege",
        Username: "Pege",
        Password: "hp",
    },
    {
        ID: "2",
        Name: "Peter",
        Username: "Pan",
        Password: "pp"
    }
];

My objective is to create a new object with empty values that mirrors the structure, shown below,

$scope.newUser = {
    ID: "",
    Name: "",
    Username: "",
    Password: ""
}

This new object will then be pushed into the existing array using

$scope.users.push($scope.newUser);
, resulting in the array looking something like this:

$scope.users = [
    {
        ID: "1",
        Name: "Hege",
        Username: "Pege",
        Password: "hp"
    },
    {
        ID: "2",
        Name: "Peter",
        Username: "Pan",
        Password: "pp"
    },
    {
        ID: "",
        Name: "",
        Username: "",
        Password: ""
    }
];

It's important to note that the structure of the array $scope.users may vary and not always contain the same set of objects. I need a method to ensure this functionality even if the array structure changes, as illustrated in the example below:

$scope.users = [
    {
        SID: "pepe",
        Name: "Peter",
        School: "Primary School"
    },
    {
        SID: "hepe",
        Name: "Hege",
        School: "Junior School"
    }
];

How can I achieve this flexibility?

Answer №1

When looking to replicate the contents of an array, start by retrieving the first object and then create a new empty object with looped keys:

if ($scope.users.length) {
    var defaultUser = $scope.users[0];

    $scope.newUser = {};
    for (var key in defaultUser) {
        $scope.newUser[key] = "";
    }

    $scope.users.push($scope.newUser);
}

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

Transform JSON time data from Coordinated Universal Time (UTC) to Indian Standard

Hello, I consider myself an amateur in the world of online javascript learning. Currently, I have come across a challenge that has left me stuck. I am working with a JSON time data provided in UTC format (e.g. 16:00:00Z) and my goal is to convert it to IS ...

Angular Directives in Error

Help needed with creating a custom directive in Angular. Seeking guidance :) I am trying to display the content from 'directive.html' within the 'app-info' directive. The code functions properly without the directive, indicating a mist ...

Releasing an ASP.NET CORE web application with AngularJS on IIS

In the process of developing a new asp.net core web app (using the full .net framework) with AngularJS version 1.5.8, we have encountered an issue. Our app is currently very basic, consisting of just one page displaying student data in a table. When runn ...

Using React: Implementing conditional checks within the render() method of functional Components

When working with my usual React class Components, I typically perform some checks within the render() method before returning conditional html rendering. However, when using a react functional component, I noticed that there is no render() method availabl ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

How can I effectively compress and decompress UTF-8 data using zlib?

My task involves handling a lengthy JSON message that contains non-ASCII characters. To convert it into a string, I use the following method: messStr = json.dumps(message, encoding='utf-8', ensure_ascii=False, sort_keys=True) However, I face a ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Create a new ArrayList in Spring Boot by using the @RequestBody annotation

Here is the code snippet I am working with: @RequestMapping(value = "/checkInventory", consumes = "application/json", method = RequestMethod.POST) @ResponseBody public ResponseEntity<?> checkInventory ( // HEADERS @RequestBody CheckInventory ...

Dynamic Reading of JQGrid Colmodel and ColNames from ASPX CodeBehind

We're in the process of upgrading our grid system to JQGrid. Our goal is to dynamically bind the grid from the code behind, including the ColModel and ColNames. The column names and model will be determined at runtime. We've attempted the follo ...

Ways to engage with a fixed html page generated by an Express router?

Let me start by mentioning that I am relatively new to working with NodeJs. Currently, I am dealing with a situation where I need to render a static HTML web page (which includes JavaScript code) as a response to a post request. Below is the relevant snipp ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Unexpected Type Error: Unable to Assign 'Render' Property to Undefined

At the moment, I am encountering these specific issues: An Uncaught TypeError: Cannot set property 'render' of undefined The element #main cannot be found This is the code that I currently have. Despite looking for solutions from various sourc ...

Update the document by sending the data and making changes based on the AJAX response

Currently, I am avoiding using jQuery and trying to work with the following code in PHP: <?php header ( 'Content-Type: text/xml; charset=utf-8' ); $con = @mysql_connect ( "localhost", "root", "" ) or die ( "Couldn't connect to database" ...

Tips for successfully passing an object as a prop in nextjs

Struggling to understand how to pass an object as a prop using useState in Next JS. My javascript functions include a lorem ipsum generator, housed in a component called Paragraphs. This component requires two properties: Number of paragraphs Sentence le ...

Completely different method for transmitting an array to NodeJS through AJAX

Recently, I've encountered difficulties when sending arrays to NodeJS using AJAX. It seems that whenever I try to send it with JSON, the error function is always triggered. Despite seeking explanations, I haven't found a satisfactory answer. The ...

You have attempted to make an invalid hook call in the react chat app. Hooks can only be called within the body of a function component

Encountering problems like manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. **Important Error Message/User Notification:** react-dom.development.js:20085 The above error occurred in the <WithStyles(ForwardRef(AppBar))> component: Arrange ...

What is the best way to apply attributes to all titles throughout a webpage?

My goal is to locate all elements on the page that have a title attribute and add a new attribute to each of them. For example: <div title='something 1'></div> <p>Test<div title='something 2'></div></p ...

The spinning loading wheel on Firefox persists even after submitting the iFrame

I have encountered a strange issue with Firefox that I can't seem to figure out. In my system, AJAX is used to send data to a PHP API. However, when file uploads are involved, Firefox does not use XMLHttpRequest() and instead reverts to submitting the ...

Utilizing Google Web Fonts in Gatsby with Custom Styled Components

While using createGlobalStyle from styled-components for global styling, everything seems to be working fine except for applying Google fonts. I have tried multiple ways but can't seem to get it to work. Here's the code snippet: import { createG ...

What is the method for linking events across multiple objects?

When a user clicks on the confirmation button in a Twitter Bootstrap modal window, I trigger a deletion action on the page. The modal contains two buttons - one for canceling the action and another for confirming it. Once the user confirms the delete act ...