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

Simple method for adapting async/await function to function smoothly with observables

From my understanding, it's not recommended to use async/await methods in Angular. Therefore, I am exploring alternatives to achieve the desired functionality without using those methods. Currently, I am utilizing the canActivate function which call ...

The term 'Component' is not a valid JSX component that can be used

'Component' is causing issues as a JSX component The error appears to be within the _app.tsx file of my Next.js project. I've been struggling with this problem since yesterday, encountered it during deployment on Vercel for my Next.js TypeS ...

The installation of @grpc/grpc-js does not include all necessary dependencies

Recently, I incorporated @grpc/grpc-js into my project using the command npm i @grpc/grpc-js. Surprisingly, there are no compile time errors when I attempt to use it. However, at runtime, a series of errors arise: ./node_modules/.pnpm/@<a href="/cdn-cgi ...

Creating a unique custom view in React Big Calendar with TypeScript

I'm struggling to create a custom view with the React Big Calendar library. Each time I try to incorporate a calendar component like Timegrid into my custom Week component, I run into an error that says react_devtools_backend.js:2560 Warning: React.cr ...

Using NgControl with a Custom Directive in Angular 2

Using ngControl on a custom component has been a challenge for me. I successfully created the component and implemented ControlValueAccessor but encountered issues with updating form classes (ng-pristine, ng-touched, ng-invalid) and checking the value of t ...

Issues encountered with the `npm install` command in Azure build pipelines for a simple Angular application

Transferred the GitHub Repository mentioned in this link to Azure Repository. Established the Build Pipeline using Classic Editor, and you can find the YAML Code below: trigger: branches: include: - refs/heads/master jobs: - job: Job_1 display ...

Ways to call a DIV element in a PHP file from a different PHP file

I am facing an issue with referring to a specific <div> element from one .php page to another. The current code is redirecting me to the home page of the first page, instead of displaying the desired content. Can anyone provide guidance on how to ach ...

When you try to remove an element from an array by its index in Vue JS, the outcome may not be

Here is an array that I have: var hdr = ("name", "date", "start_time", "selling_item", "total_call", "end_time", "ad_num", "area", "order_num"); //this data comes from the database Now, I need to rename these array elements according to prope ...

navigate to a new page in vue with node.js

As I continue to expand my knowledge in JavaScript, Vue, and Node.js, I encountered a specific issue that I need help with. My goal is to redirect the Vue page after logging in using Node.js. Below you'll find the code snippets for my Vue setup and sc ...

Understanding JavaScript Regular Expressions

To ensure that no HTML tags are entered into a textarea, I am utilizing the following regex for validation. If any HTML tags are detected in the textarea, I need to display a validation message. The regex being used is: /<(\w+)((?:\s+\w ...

Why is the script from URL "http://.../js/myscript.js" not executing as expected after being fetched?

Is it possible to have the server run a JavaScript file specified in a URL, such as "http://.../js/script_name.js", and return the result instead of just displaying the source code? I am assuming that the server is using node.js. ...

What is the process for obtaining the result and storing it in an array using M

Recently, I just started exploring angular and ventured into using mongoose with mongodb. Within my application, I require a list of driver names in the form of a string array. However, instead of receiving a simple array of names, I am getting an array o ...

Is there a way to modify certain parameters of a plugin without the need to directly edit the

Is there a way to modify certain parameters of a plugin without directly editing it? You can find the link to the plugin here: . Can we include an additional script to override specific parameters of the above script, such as setting displayTime to 1000 ...

How to Force a jQuery Redraw Following Data Retrieval Using Ajax

Hey everyone, It's been a long time since I started listening, but this is my first post... I have a client who needs a complex feature on their website. They want to merge the content of 3 different pages into one seamless experience for users afte ...

Embed fashion and graph elements into a CSV document (generated from <script>)

Encountering an issue with my code. I am looking to export an HTML table to a CSV file (specifically Libre Office Calc, regardless of csv, xls or xlsx format, as long as it runs on a Linux Server). Found a script online that works well after some modificat ...

Firebase authentication encountered an error due to a network request failure

Utilizing firebase Hosting to host my website, I am encountering a persistent error when attempting to login using email/password. This is the JavaScript code that I am using: window.onload = () => initApp(); //Initialize screen function initApp(){ ...

Properties undefined

All of my functions are giving errors indicating that the props are not defined. The error specifically relates to the word "props" in the following functions: function PostButton(props) function PostButton2(props) function TotalVotes(props) ...

Adding a background image in javascript using data from a MySQL database

My current tech stack includes CodeIgniter, vanilla JavaScript, AJAX, CSS, and MySQL. I am trying to figure out how to set the background of an image that is stored in a MySQL database. While the following code is error-free and working perfectly, my cha ...

Adjust an OnDemandGrid utilizing dstore/Rest output through a POST request instead of a PUT request

I am facing a perplexing issue. I have an OnDemandGrid that is editable, and below it, I have a dstore/Rest collection connected to my backend (using PHP). While I can edit the data in the OnDemandGrid, I am unable to save it properly. When it reaches the ...

Different ways to analyze elements from 2 arrays to hone in on specific values

I'm really struggling to solve this issue. I have two arrays - one for cars and the other for active filters. The cars array consists of HTML li tags with attributes like car type, number of seats, price, etc. On the other hand, the active_filters arr ...