Combine the object with TypeScript

Within my Angular application, the data is structured as follows:

  forEachArrayOne = [
    { id: 1, name: "userOne" },
    { id: 2, name: "userTwo" },
    { id: 3, name: "userThree" }
  ]

  forEachArrayTwo = [
    { id: 1, name: "userFour" },
    { id: 2, name: "userFive" },
    { id: 3, name: "userSix" }
  ]

  newObj: any = {};

  ngOnInit() {
this.forEachArrayOne.forEach(element => {
  this.newObj = { titleOne: "objectOne", dataOne: this.forEachArrayOne };
})

this.forEachArrayTwo.forEach(element => {
  this.newObj = { titleTwo: "objectTwo", dataTwo: this.forEachArrayTwo };
})

console.log({ ...this.newObj, ...this.newObj });


  }

In my actual application, I have the above structure and I need help to achieve the expected output in a similar manner.

You can find a live demonstration here on StackBlitz, demonstrating the mentioned structure.

At present, when I use console.log(this.newObj), only the last object is displayed:

   titleTwo: "ObjectTwo",
   dataTwo:
     [
       { id: 1, name: "userFour" },
      { id: 2, name: "userFive" },
      { id: 3, name: "userSix" }
     ]

However, I want to merge both structures and obtain the following result exactly:

  {
  titleOne: "objectOne", 
  dataOne:
    [
      { id: 1, name: "userOne" },
      { id: 2, name: "userTwo" },
      { id: 3, name: "userThree" }
    ],
  titleTwo: "ObjectTwo",
  dataTwo:
    [
      { id: 1, name: "userFour" },
      { id: 2, name: "userFive" },
      { id: 3, name: "userSix" }
    ]
}

Please assist me in achieving the desired outcome. If there are any errors in my code, kindly provide corrections along with a working example. Thank you!

Answer №1

When you assign both values to this.newObj, the first object gets overwritten.

Your loop is unnecessary and doesn't add any value.

A better approach would be:

this.newObjA = { titleOne: "objectOne", dataOne: this.forEachArrayOne };
this.newObjB = { titleTwo: "objectTwo", dataTwo: this.forEachArrayTwo };
console.log({ ...this.newObjA, ...this.newObjB });

EDIT:

After discussing your requirements, I have a different solution in mind.

Prior to calling componentData, ensure that you have all the necessary data by using forkJoin to merge benchmark requests and project requests into one Observable. Then, subscribe to that Observable to retrieve the results for both.

The code should resemble something like this:

 // Code snippet
  

Check out this Stackblitz example showcasing the console log of the data

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

Concealing Contact Form Using Javascript

Upon making adjustments to a website, I encountered an issue with the contact form. The form is meant to be hidden on page load and only appear when the envelope icon is clicked. However, currently the form is visible by default, and clicking the envelope ...

JavaScript can be used to create dynamic frames within a

Can anyone help identify the issue in my code? frame 1 <script type="text/javascript"> var Clicks = 0 ; function AddClick(){ Clicks = Clicks + 1; document.getElementById('CountedClicks').innerHTML = Clicks ; } localStorage.setItem(' ...

Angular 8 throwing an ExpressionChangedAfterItHasBeenCheckedError when a method is called within the ngOnInit function

I encountered a common issue with an Angular template. I have a standard template for all my pages, containing a *ngIf directive with a spinner and another one with the router-outlet. The behavior and visibility of the spinner are controlled by an interce ...

AngularJS is not responding to a 400 bad request

Despite my efforts to find solutions on Google and Stack Overflow for similar or identical issues, as a newcomer, none of them have provided me with any insight on how to resolve the issues in my code. Here is the script I am working with: $http.post(&ap ...

Retrieve the HTML data and save it as page.html, displayed in a VueJS preview

After developing an innovative VueJS-based application for managing front-end content, I am now eager to enhance it with a 'download' button feature. This new functionality will allow users to easily download the previewed and edited content in H ...

The potential object null may lead to an absence of the 'value' property in the type 'EventTarget'

I am facing a problem that I am unable to resolve. The error in my HTML reads: Object is possibly 'null' and Property 'value' does not exist on type 'EventTarget'. HTML <select [(ngModel)]="selectedProvincia" (ch ...

What causes jquery height and javascript height to both be returned as 0?

I'm facing an issue with a visible div on my screen - despite being visible, its height always returns as 0. I've attempted various jQuery and JavaScript methods to retrieve the height, but it consistently shows as 0. Here's the structure of ...

Any ideas on how to format a date for jQuery Datepicker?

Currently, I have implemented two different datepickers on my website, but I am interested in switching to jQuery's Datepicker for a more unified solution. Here is the current format that I am sending to our backend API: However, I would prefer to i ...

Working with XML files in Node.js

I'm currently running an Arch Linux system with KDE plasma and I have a 50mb XML file that I need to parse. This XML file contains custom tags. Here is an example of the XML: <JMdict> <entry> <ent_seq>1000000</ent_seq&g ...

Troubleshooting: Dealing with Stack Overflow Error when using setInterval in Vue Programming

I am facing a stack overflow error while creating a timer using Vue, and I'm struggling to understand the root cause. Can someone provide insights on the following code: Here is my template structure: <span class="coundown-number"> { ...

What is the best way to remove data from both arrays simultaneously?

I am working with a grid that displays a list of time ranges. For example: timeList=[{from:12:00:00 , to:14:00:00 ,id:10}{from:08:00:00 , to:09:00:00 ,id:11{from:05:00:00 , to:10:00:00 ,id:12}}] time=[{Value:12:00:00 id:10} {Value:14:00:00 id:100} ...

Encountering an 'undefined' property error when clicking a button in Angular 1.x

Hey there, I have a question that might seem simple to some of you. I'm struggling with fixing an error and I don't quite understand why it's happening :( This error popped up while using Angular 1.x. What I need help with is creating an al ...

The generated hook in vuejs is throwing an error stating that window/localstorage is not defined

My goal is to save an authenticated user to local storage and then load them into Vuex on the next page load. created () { let user = window.localStorage.getItem('user') if(user) { this.setUser(JSON.parse(user)) } } I initia ...

Separating the logic of identical schemas and implementing multi-tenancy in Node.js using Mongoose

In the system I am developing, there are two key requirements: Each client needs to be completely isolated from one another Clients can have multiple subsidiaries which they should be able to switch between without needing to re-authenticate, while ensuri ...

When setupFilesAfterEnv is added, mock functions may not function properly in .test files

Upon including setupFilesAfterEnv in the jest.config.js like this: module.exports = { preset: 'ts-jest', testEnvironment: 'node', setupFilesAfterEnv: ["./test/setupAfterEnv.ts"] } The mock functions seem to sto ...

attempting to shift course, but finding no success

I'm attempting to include dir=rtl or direction: rtl in the CSS, but it doesn't seem to have any effect on the browser and the content still displays left to right. What steps can I take to fix this? This template is pre-made from Colorlib. It&ap ...

Converting JSON DateTime objects to local time in JQuery without considering timezones

I am struggling with parsing a JSON DateTime object using moment.js. Despite trying various methods recommended on Stackoverflow, nothing seems to work in my case. In my application, I save DateTime values in UTC format and when displaying them, I need to ...

"Upon completing an AJAX file upload, both $_POST and $_FILES arrays are found

Recently, I've delved into the realm of web development and encountered a hurdle with ajax file uploading... My current setup involves two HTML input fields: one for files and another for a button. <input type="file" name="Frame" id=" ...

What is the best way to distribute components between two NextJS projects?

Confused about the best way to share ReactJs components between two NextJs applications - one for e-commerce and the other for a manager portal. In the e-commerce app, there are various UI components that I want to reuse in the manager portal. Considering ...

Node.JS program unexpectedly logging MySQL results to console and exhibiting erratic behavior

Recently, I encountered a peculiar error while working with Node.JS MySQL. Strangely, I noticed that a result was being logged in the console without any corresponding code line instructing it to do so. Even more baffling was the fact that when I intention ...