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

Is it possible to declare a variable as both $rootScope and $scope within the same controller?

Is it possible to declare a variable as both $rootScope and $scope in the same controller? $scope.Account=[{'sdfdsf','sdfds'}]; $scope.refreshAccountSummary = function () { Report.account(function (res) { $rootScope.Account ...

It's time to wrap up the session with some old "cookies" and a closing function

Would like the message to only display once after clicking the "Cookies" button. Once the user accepts cookies, they should be stored on their device for a set period of time. Your assistance is greatly appreciated. :) Below is the html and js code: $(do ...

Can someone help me identify the issue with my JavaScript code?

Recently, I attempted to transfer data from JavaScript to HTML using Angular. Here is the code snippet: phonecatControllers.controller('start', ['$scope', function($scope){ $scope.lloadd=true; console.log('data - '+$ ...

Python ValueError: Unable to decode JSON as a valid object despite the JSON being correctly formatted

My JSON file was valid (verified using this website) but suddenly it cannot be read. This script has been functional for a long time. I'm unsure what caused the issue. Here is the script: import os import json basepath = '/path/' for entr ...

Retrieve numerical values from a JSON file using PHP

The code I currently have is causing an issue: $json = file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=0'); $coins = json_decode($json, true); foreach($coins as $coin) { echo $coin->24h_volume_usd; } Upon running the scri ...

Setting a global variable in the JavaScript code below

Is there a way to make the modal variable global by setting it as var modal = $("#modal"); ? The code snippet below includes the modal variable and is not functioning properly. It needs to work correctly in order to display: "Hello name, You have signed u ...

A guide on fetching the selected date from a datepicker in framework7 with the help of vuejs

Here is a snippet of the code for a component I am working on: <f7-list-input label=“Fecha de nacimiento” type=“datepicker” placeholder=“Selecciona una fecha” :value=“perfil.fecha_nacimiento” @input=“perfil.fecha_nacimiento = $event.t ...

Is it possible to display CKEditor5 toolbar buttons in a separate row rather than the primary row?

https://i.stack.imgur.com/Tyfqb.png I successfully integrated CKEditor5 into my create react app directly from the source code. However, I am facing an issue where the overflowed buttons in the toolbar are being displayed in a separate menu item instead o ...

Arranging objects in an array based on a separate array of strings

Here is an array of objects that I need to rearrange: var items = [ { key: 'address', value: '1234 Boxwood Lane' }, { key: 'nameAndTitle', value: 'Jane Doe, Manager' }, { key: 'contactEmail', value: ...

Challenges compiling 'vue-loader' in Webpack caused by '@vue/compiler-sfc' issues

The Challenge Embarking on the development of a new application, we decided to implement a GULP and Webpack pipeline for compiling SCSS, Vue 3, and Typescript files. However, my recent endeavors have been consumed by a perplexing dilemma. Every time I add ...

Troubles with Vue and localStorage for storing a theme's data

I've been struggling with this issue for a while now while working on a Vue site. I have not been able to find a solution for my specific bug in other discussions. The concept should be straightforward - I want to have a switch that toggles a value b ...

What is the best way to read JSON responses from a Unirest request in Python?

response_post =unirest.get("http://timesofindia.indiatimes.com/feeds/newsdefaultfeeds.cms?feedtype=sjson",headers={ "X-Mashape-Key": "key", "Accept": "application/json"},) What is the best way to convert the response_post into a JSON result? ...

Conflicts between Bootstrap Validator and Ajax.BeginForm in Partial Views of MVC

My current issue involves using Ajax.BeginForm to post data on a form without refreshing the entire page. The goal is to validate a textbox - if it has a value, then the data should be posted; otherwise, a validation message should be displayed. However, I ...

AngularJS ngResource failing to pass custom headers

Using ngResource to query a REST API, I am facing an issue with setting my API key in a custom header. Here is how I have attempted to do it: angular.module('ApiService', ['ngResource']) .factory('Api', ['$resource&ap ...

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 best way to activate a function from a modal component without having the function embedded in Angular 14?

I've recently been putting together an e-commerce application using Angular 14. Currently, I'm tackling a form that must only be submitted once the user accepts the "Terms & Conditions" shown in a modal popup. The FormComponent and ModalCompone ...

Snapshots in AngularJS SEO with PhantomJS can be created either before or during the crawling process

What is the best approach for generating snapshots (snapshots being a plain HTML version of an Angular state/route created for SEO purposes)? Should it be done every time an author adds a post in a blog? Or should it be generated during crawling? Link t ...

jQuery blueimp File Uploader: Transferring multiple files to the server on Internet Explorer

After customizing the demo for my Rails application, I encountered an issue with the plugin in Internet Explorer. While it works smoothly on Chrome and Firefox, in IE (all versions) it fails to upload all but one file when multiple files are selected, and ...

Using Multiline Strings for Arguments

Is there a way to successfully pass multi-line strings containing spaces and tabs as a parameter to an express server? Below is the Express.js code snippet which accepts the parameter: app.get('/:prompt', async (req, res) => { ...

Tips for developing a function that can identify the position of the largest integer within a given array

I need some help refining my function that is designed to identify the index of the largest number in an array. Unfortunately, my current implementation breaks when it encounters negative numbers within the array. Here's the code snippet I've bee ...