Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error:

Cannot set Property "account" of undefined.

This is the code in question:

    acs = [
    {
        "account": "Cash In Hand",
        "liabilities": 0,
        "assets": 8031597
    },
    {
        "account": "Tax Acs",
        "liabilities": 988363.72,
        "assets": 0.98
    },
    {
        "account": "Sundry Debtor",
        "liabilities": 0,
        "assets": 551
    },
    {
        "account": "Sundry Creditor",
        "liabilities": 0,
        "assets": 0
    }
];

acd: any;
acc: any;
newacc: any;

constructor() { }

ngOnInit() {
    this.acd = this.acs.filter(f => f.liabilities !== 0);
    this.acc = this.acs.filter(f => f.assets !== 0);

    const bigger = this.acd.length > this.acc.length ? this.acd.length : this.acc.length;

    this.newacc = [];
    for (let i = 0; i < bigger; i++) {
      if (this.acd.length > i) {
        this.newacc[i].account = this.acd[i].account;
        this.newacc[i].liabilities = this.acd[i].liabilities;
      }
      if (this.acc.length > i) {
        this.newacc[i].accounts = this.acc[i].account;
        this.newacc[i].assets = this.acc[i].assets;
      }
    }
  }

Adding this.newacc = [{}]; results in the same error occurring for the second if statement as well - specifically at this.newacc[i].accounts.

What mistake may have been made here? Is there a simpler method to combine these independent arrays side by side, considering their differing lengths and lack of associated data?

Answer №1

To resolve the issue, it is recommended to utilize the push method instead of using C++ syntax. Here is an example:

 this.newacc[i].account = this.acd[i].account;

Instead, you can use the push method and pass the desired object as a parameter like this:

newacc.push({account:acd[i].account, liabilities : acd[i].liabilities });

acs = [ { "account": "Cash In Hand", "liabilities": 0, "assets": 8031597 }, { "account": "Tax Acs", "liabilities": 988363.72, "assets": 0.98 }, { "account": "Sundry Debtor", "liabilities": 0, "assets": 551 }, { "account": "Sundry Creditor", "liabilities": 0, "assets": 0 } ];

acd = acs.filter(f => f.liabilities !== 0);
acc = acs.filter(f => f.assets !== 0);

const bigger = acd.length > acc.length ? acd.length : acc.length, newacc = [];
for (let i = 0; i < bigger; i++) {
  if (acd.length > i)
    newacc.push({account:acd[i].account, liabilities : acd[i].liabilities });
  if (acc.length > i)
    newacc.push({account:acc[i].account, assets : acc[i].assets });
}
console.log(newacc);

Answer №2

Your issue stems from a problem with Typescript, rather than any Angular-related issues.

To address part of your code, here is a solution for you to consider:

interface accnt {
  account: string;
  liabilities: number;
  assets: number;
}

let acs = [
    {
        "account": "Cash In Hand",
        "liabilities": 0,
        "assets": 8031597
    },
    {
        "account": "Tax Acs",
        "liabilities": 988363.72,
        "assets": 0.98
    },
    {
        "account": "Sundry Debtor",
        "liabilities": 0,
        "assets": 551
    },
    {
        "account": "Sundry Creditor",
        "liabilities": 0,
        "assets": 0
    }
];

let acd: accnt[] = new Array(4);
let acc: accnt[] = new Array(4);
let newacc: accnt[] = new Array(4);

this.acd = this.acs.filter(f => f.liabilities !== 0);
this.acc = this.acs.filter(f => f.assets !== 0);
alert(JSON.stringify(this.acd));
alert(JSON.stringify(this.acc));
alert(JSON.stringify(this.newacc));

const bigger = this.acd.length > this.acc.length ? this.acd.length : this.acc.length;

for (let i = 0; i < bigger; i++) {
  if (this.acd.length > i) {
    this.newacc[i] =
      {
        account: this.acd[i].account,
        liabilities: this.acd[i].liabilities
      }
  }
  /*if (this.acc.length > i) {
    this.newacc[i].accounts = this.acc[i].account;
    this.newacc[i].assets = this.acc[i].assets;
  }*/
}

alert(JSON.stringify(this.newacc));

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 the behavior of a function with synchronous AJAX (XMLHttpRequest) call in JavaScript (Vanilla, without jQuery) the same as asynchronous?

I'm facing an issue with a file named tst.html and its content: part two (purely for demonstration, no extra markup) The challenge arises when I try to load this file using synchronous AJAX (XMLHttpRequest): function someFunc() { var str = &ap ...

Angular is unable to load additional routes

While working on building a web application with Angular 11, I encountered an issue with routing. When navigating from the initial route ( { path: '', component: HomeComponent } ) to other routes, everything functions as expected. However, when ...

Location of Ajax callback function

I encountered an issue with a callback function that was placed within $(document).ready. The callback function wasn't functioning as expected. Surprisingly, when I moved it outside of $(document).ready, the code started working flawlessly. I am puzzl ...

Tips for moving an element to the end of an array

Patients' data is stored in the MongoDB database, and all patients are mapped through on the frontend to display a list. An additional boolean value indicates whether a patient is archived or not. If a patient is archived, it should be displayed at th ...

Understanding Pass by Reference within Objects through Extend in Javascript with underscore.js Library

When working with Javascript and using the extend function in the underscore.js library, I am curious about what happens in relation to memory. Consider this example: var obj = {hello: [2]}; var obj2 = {hola: [4]}; _.extend(obj, obj2) obj2.hola = 5; conso ...

Ways to prompt the debugger to pause whenever a specific script file is called during execution in Edge/Chrome debugger

I am currently in the process of debugging a Typescript web application, which is quite new to me as I have never delved into web development before. This particular project entails multiple script files and various libraries. While running the applicatio ...

Executing multiple server-side methods on an AJAX call in ASP.NET MVC: A comprehensive guide

I am facing a situation where I have a method that is called by jQuery, and its result is displayed on a popup. Sometimes, it takes some time to complete and a blank popup appears with processing message. When clicking on close, the popup disappears but th ...

Implementing the OnClick method for the button component

After successfully creating a reusable button component, I now want to assign different onClick links to each Button component. How can I achieve this? import styled from 'styled-components' const Button = styled.button` background: #0070f3; ...

"Enhancing the user experience: Triggering a window resize event in jQuery before page load on Magento

I am trying to trigger this function before the page finishes loading, but currently it only triggers after the page has loaded. Can anyone assist with this issue? $(window).on('load resize', function(){ var win = $(this); //this = window ...

Angular Testing: Simplify module setup by using Testbed in each test suite

Currently, I am utilizing a third-party Angular component library that consists of widgets built on web components. It takes approximately 3 seconds for all the web components to be registered. Each time I need to run a test, I have to wait for the librar ...

What is the correct way to properly deploy Nuxt.js in SPA mode on a server?

My current project involves utilizing Nuxt.js in Single Page Application (SPA) mode. However, I am encountering difficulties when trying to deploy it on my Apache server. Has anyone else faced this issue before? I suspect that the problem may be related t ...

Is it possible to use next.js to statically render dynamic pages without the data being available during the build process?

In the latest documentation for next.js, it states that dynamic routes can be managed by offering the route data to getStaticProps and getStaticPaths. Is there a way I can create dynamic routes without having to use getStaticProps() and getStaticPaths(), ...

Angular directive specifically meant for the parent element

I am working on a directive that I need to apply to a specific div element without affecting its child elements. The goal is to make the main div draggable, so that when it moves, its child divs move along with it. However, I do not want the child divs to ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

Invoker of middleware and stack functions for Express.js with a focus on capturing the response object

It appears that the expressjs app contains a stack of Layer object Arrays. What function is utilized to pass the I am curious about: When a request is sent from the http client, which function is called first and how are the stack array functions with mi ...

Buttons for camera actions are superimposed on top of the preview of the capacitor camera

I am currently using the Capacitor CameraPreview Library to access the camera functions of the device. However, I have encountered a strange issue where the camera buttons overlap with the preview when exporting to an android device. This issue seems to on ...

An error occurred while defining props due to a parsing issue with the prop type. The unexpected token was encountered. Perhaps you meant to use `{`}` or `}`?

const dataProps = defineProps({ selectedData: <Record<string, string>> }); Under the closing bracket, there is a red line indicating: Error: Unexpected token. Consider using {'}'} or &rbrace; instead?eslint Expression expecte ...

linking to a page that shows the user's chosen option from a dropdown menu

One of the challenges I encountered was creating a feature that allows users to share a specific selection from multiple dropdown lists on a page. Essentially, my goal was to enable users to send a link that would direct others to the same page with the ex ...

Angular Material Datepicker: Changing the input field format when the field value is updated

Currently, I am utilizing a mat-date-rang-input component from Angular Material. To customize the date format to dd/MM/yyyy, I made adjustments within Angular Material which is functioning correctly. <mat-form-field ngClass="filters_dateInterval&qu ...

Angular refreshes outdated DOM element

Within my Angular (v9) application, I have a simple component. The main goal of this component is to display the current date and time when it is first shown, and then after a 2-second delay, enable a button. Here's the code snippet from app.component ...