To form a new array object, merge two separate arrays into one

https://stackblitz.com/edit/angular-enctgg-dvagm3 Issue: Attempting to update the hours from arr2 to arr1 and create the desired output below.

Trying to achieve this using map function, but unsure how to navigate through nested arrays. Note: Array1 contains nested arrays which need to be mapped with array2 code :

var result = this.responseValue.map((person, index) => ({ ppmInfoId: { locationCode: person.locationCode, yearMonth: person.locationType, changeOrderId: 20 },  hours: index}));

Desired output :

"ppmInfo": [
  {
    "ppmInfoId": {
      "changeOrderId": 0,
      "locationCode": 1,
      "yearMonth": "May/2021"
    },
    "hours": "10"
  },
  {
    "ppmInfoId": {
      "changeOrderId": 0,
      "locationCode": 1,
      "yearMonth": "June/2021"
    },
    "hours": "20"
  },
  {
    "ppmInfoId": {
      "changeOrderId": 0,
      "locationCode": 2,
      "yearMonth": "May/2021"
    },
    "hours": "10"
  },
  {
    "ppmInfoId": {
      "changeOrderId": 0,
      "locationCode": 3,
      "yearMonth": "May/2021"
    },
    "hours": "10"
  }
]

Input Array 1 :

 this.responseValue = [
          {
            locationCode: '1',
            locationType: 'Onsite',
            ppmDetailsToList: [
              {
                hours: 0,
                changeOrderId: null,
                yearMonth: 'May/2021',                
              },
              {
                hours: 0,
                changeOrderId: null,
                yearMonth: 'June/2021',                
              },
            ]
          },
          {
            locationCode: '2',
            locationType: 'Offshore',
            ppmDetailsToList: [
              {
                hours: 0,
                changeOrderId: null,
                yearMonth: 'May/2021',                
              },
            ]
          },
          {
            locationCode: '3',
            locationType: 'offsite',
            ppmDetailsToList: [
              {
                hours:0,
                changeOrderId: null,
                yearMonth: 'May/2021',
                locationCode: 0
              },
            ]
          }
        ];

Input array 2 :

[{ "Onsite": [ 10, 20 ], "Offshore": [ 10 ], "offsite": [ 10 ] }]

Answer №1

const data = [{
    postCode: '12345',
    postType: 'Residential',
    detailsList: [{
      quantity: 5,
      orderID: null,
      deliveryDate: 'June/2021',
    }, ]
  },
  {
    postCode: '54321',
    postType: 'Commercial',
    detailsList: [{
      quantity: 10,
      orderID: null,
      deliveryDate: 'June/2021',
    }, ]
  },
  {
    postCode: '67890',
    postType: 'Industrial',
    detailsList: [{
      quantity: 7,
      orderID: null,
      deliveryDate: 'June/2021',
      postCode: 15
    }, ]
  }
];
const inventory = [{
  "Residential": [50],
  "Commercial": [100],
  "Industrial": [70]
}]

const finalResult = {
  orderDetails: data.map(({ 
    postCode, 
    postType, 
    detailsList: [{ quantity, orderID, deliveryDate }]
  }) =>({
    quantity: inventory[0][postType][0],
    orderInfoId: {
      orderID: orderID || 0,
      postCode,
      deliveryDate
    }
  }))
}

console.log(finalResult)

Answer №2

We utilized foreach in order to achieve the expected result. Concluding this process.

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

Transforming a text string obtained from a file into a JSON object using Node.js

I have a scenario where I am retrieving a string from a file and then looking to convert it into a json object. File content: {name:"sda"} Here is the code snippet: var fs=require('fs'); var dir='./folder/'; fs.readdir(dir,function(e ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...

Is there a way to dynamically insert my own <divs> into a container?

I've been doing a lot of research on this issue, but I haven't come across any solutions that have been helpful so far. The problem I'm facing is that I have a div with an id that is supposed to act as a container (#cont_seguim). On the rig ...

Demonstrating the process of sending a list of items from Angular to an Express API connected to MongoDB

I am currently working on developing an Express Mongo API that is being utilized by an Angular application. My query revolves around posting a list of items. Here is my MongoDB schema: var TestSchema = new mongoose.Schema({ title: String, colors: ...

What is the process of importing a jQuery library into Vue.js?

Converting an HTML template to a Vue.js application with Laravel has been quite the task. One particular function that I am struggling with is the drag and drop table feature. src="assets/js/jquery.dataTables.min.js"> src="https://cdnjs.cloudflare.co ...

Tips for Implementing Cache Busting in Angular Universal

Is there a way to execute cache busting in Angular Universal? I attempted to run the command npm run build:ssr --output-hashing=all but it did not make any changes. PACKAGE.json "scripts": { "ng": "ng", "start": "ng serve", "build": "ng bui ...

Is there a way to automatically assign a default value to radio buttons when the page is loaded?

Working with OpenERP 7, I encountered a problem with two radio buttons that should change the values of a table. After creating an event that triggers a Python function to execute an SQL query, I found that upon reloading the page, the radio buttons revert ...

Simplifying complex JSON structures by un-nesting arrays

Within my Formik form, I have 3 fields: MemberMemberID, EventEventID, and event_date. This form represents an event (such as a Tuesday club) taking place on a specific date and attended by various members. Formik stores the data in key-value pairs within ...

Using Conditions in a Javascript For Loop

I would like to utilize a for loop to achieve the following task. Within an array, I have a predefined set of values representing hex colors for a chart. My goal is to extract a specified number of those values using the loop with two options. If the ...

"Enhance Your Search Input with Dynamic Suggestions from JSON Data Integrated with

Hello! I am looking to create an autosuggest feature using a PHP file that returns a JSON Object. I then parse it in JavaScript to generate a link with the correct ID (refer to the provided JSON data). JSON data from search_new.php: {"Data":{"Recipes":{ ...

An effective method for transferring form input and music between pages utilizing JavaScript

I've been grappling with this issue for quite some time now. On the initial page, I have a form like this: <form id="user" name="user" method="GET" action="the-tell-tale-heart.html"> Name: <input type="text" name="name"> & ...

Is there a way to connect a Button to a different page in VUE.JS?

I currently have a button that needs to be linked to another page. This is the code I am working with at the moment. How can we write this login functionality in vue.js? It should direct users to the page "/shop/customer/login" <div class="space-x ...

When implementing protractor spyOn() with jQuery's ajax() function, an error is triggered stating 'ajax() method is non-existent'

I am currently testing the functionality of using AJAX to submit a form. Below is the Protractor code for the test: describe('login.php', function() { it("should use ajax on submit", function() { browser.get('/login.php'); spyOn($ ...

Issue with the iOS gyroscope detected when rotating specifically around the z-axis

I am facing a unique challenge with an unusual bug and I'm looking for help from anyone who has encountered this issue before or can provide a solution. My current project involves using Javascript to access the gyro on iOS devices, specifically focu ...

What are the reasons behind memory leaks and decreased rendering speed when I exit and then reopen a React component (specifically Material-Table)?

I have been working on a basic React example for learning purposes, and I incorporated the use of material-table in one of my components. However, I noticed that each time I change pages and reopen the component (unmount and mount), the rendering speed of ...

PHPExcel - Converting array values to strings when uploading into cells

$objPHPExcel->getActiveSheet()->fromArray($dataArray,null,"A2") I have the code above but I struggle with iterating. I want all cell values to be treated as strings to prevent automated modifications that may remove leading zeros. P.S. Any guidance ...

Restricting Checkbox Choices with JavaScript by Leveraging the forEach Function

I am developing a checklist application that limits the user to selecting a maximum of three checkboxes. I have implemented a function to prevent users from checking more than three boxes, but it is not working as expected. The function detects when an ite ...

The HTTPS protocol seems to be causing CORS issues, but I can access http://localhost without

In my current project using TypeScript with Express, I encountered an issue with implementing CORS. In the past, I have successfully added CORS to regular Express.js projects without TypeScript and assumed it would work similarly. However, when making a ba ...

Encountered an unexpected symbol < in JSON while implementing fetch() operation

I'm currently working on linking my React signup page to my Django API in order to automatically create a user profile in Django when a user signs up. Whenever I attempt to create a new user, I encounter this error in my console: Signup.js:33 ...

"OBJLoader Three.js r74, bringing vibrantly colored elements to your 3

It's a straightforward process, I import my OBJ model that was exported using 3DS Max. I have the intention of coloring a specific section of the Object. During the animation loop, I implement the following: scene.traverse( function( object ) { ...