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

Sync State with Data from API Query

I have a scenario where I need to fetch data from two different APIs and update their states separately. Afterward, I am iterating through the NBA data and looping through the animeData object to update the allData state, which will be an array of object ...

Nextjs: utilizing static class or employing a use function

Exploring Methods to Create a Tools Class/Function in NextJS I am considering two different approaches for this task. Using Static Class: class Tools { static titleCase(value: string) { return value.charAt(0).toUpperCase() + value.slice(1). ...

Reload the Node.js webpage

Is there a method to automatically refresh a Node.js page following a socket.io event? var messageDynamic = "Initial status"; app.get("/", function(request, response) { response.setHeader('Content-Type', 'text/plain'); respons ...

What is the best way to take any constructor type and transform it into a function type that can take the same arguments?

In the code snippet below, a class is created with a constructor that takes an argument of a generic type. This argument determines the type of the parameter received by the second argument. In this case, the first parameter sets the callback function&apos ...

What is the best way to retrieve the parameter of ng2-file-upload using endback?

I am attempting to retrieve a parameter using PHP in order to save it into a folder. However, my code is not working as expected. Here is the code snippet: Using the Ionic framework this.uploader.onBeforeUploadItem = (item: any) => { this.uploader ...

Troubleshooting the issue: Difficulty in activating Navbar dropdown using Angular and ui-router

I've been struggling with this issue for some time now - trying to make a simple bootstrap navbar dropdown function properly with angular ui-router and ui-bootstrap (1.3.3, the latest version). Below is my current code: <div class="container"> ...

How to use a string condition to filter a list of objects in Javascript?

Below is the structure of the object: var objList = [ { "age": 19, "valueField": 34, "booleanField": false }, { "age": 15, "valueField": 5, "booleanField": false }, { "age": 22, "valueField": 17, "booleanField": true } ]; Given the condition ...

Update the icon in real-time based on the text with Angular 8 and Font Awesome, achieving dynamic changes effortlessly

I need to dynamically change the icon based on the value within a span element. Here is the HTML structure: The version text will only have two possible values: If the value is "Active", then a success icon should be displayed. If the value is "Inactive ...

What is causing the groupBy function from rxjs in Angular to malfunction?

After mapping my object and applying groupBy, the grouping does not work as expected. Let me demonstrate. this.accountService.list(acc1).pipe( map((ac :any) => ac.list), groupBy(x => x.currency), mergeMap(group => group.pipe(toA ...

Shifting the placement of a component in Vue JS when hovering the mouse

I am facing an issue regarding the positioning of components. I have four images, and when you hover over them, a specific component is displayed as shown below: For example, hovering over a yellow image will display a different component below it, and so ...

Angular's innerHTML dilemma

Within my Angular service, I have implemented three methods as shown below: public loadLiveChat() { let url: string; url = this.appConfig.config.liveAgent.liveAgentScriptUrl; this.dynamicallyLoadScript(url); ...

How can one check in JavaScript if a specific URL was targeted with a XMLHttpRequest?

While I am familiar with monitoring network traffic in the browser's development tools and having XMLHttpRequests shown in the console, I am curious if there is a specific window property that showcases all network activity at once? ...

What is the best way to verify if an object is an instance of a particular class using Jasmine testing?

In the process of developing an Angular application, I am currently working on testing a component using this guide. My goal is to ensure that when my ngOnInit() method is called, it correctly initializes my foos property with an array of Foo objects based ...

How can I retrieve the length of an array in vuejs?

This snippet includes a script tag <script> export default { data() { return { blogs: [], }; }, created() { this.paginate_total = this.blogs.length / this.paginate; }, }; </script> Displayed below is the respo ...

Can the Angular Material Mat Stepper display multiple active/in-progress steps simultaneously?

Has anyone figured out how to display multiple steps simultaneously on Angular Mat Stepper? I've only been able to show one step at a time and haven't found a solution yet. Any insights would be greatly appreciated. https://i.stack.imgur.com/VK ...

Customize the initial color of the text field in Material UI

I am currently working with the mui TextField component and facing an issue. I am able to change the color when it is focused using the theme, but I cannot find a way to adjust its color (label and border) in its initial state when it's not focused. I ...

How to toggle two classes simultaneously using JQuery

Check out this code snippet: http://jsfiddle.net/celiostat/NCPv9/ Utilizing the 2 jQuery plugin allows for the following changes to be made: - The background color of the div can be set to gray. - The text color can be changed to red. The issue arises wh ...

Issues with using a personalized font in a Stenciljs project

Looking for guidance on implementing a custom font in my Stenciljs app. I have the otf file, unsure if an npm package is necessary. Here's my code: filestructure: -src --components --assets ---Anurti-Regular.tiff ---Anurti-Regular.ttf friends-l ...

Guide on configuring and executing AngularJS Protractor tests using Jenkins

I am encountering an error with the following configuration: ERROR registration capabilities Capabilities [{platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=}] does not match the current platform LINUX 18:17:05.892 INFO ...

Guide on darkening the surrounding div of an alert to give it a modal-like effect

I want to display an alert to the user in a visually appealing way. To achieve this, I am utilizing Bootstrap's alert class. Here is how I am showing the user a div: <div class="alert alert-warning alert-dismissible" role="alert"> Some text ...