What is the process of combining two objects in TypeScript?

As part of my project, I am using two different get requests. The first request returns data in the form of: department: string[]

The second get request provides an object structured like this:

globalObj: {
  count: number[],
  admin: {
    department: string,
    email: string,
    img_path: string,
    name: string
  }[]
}

I aim to merge these two objects together to achieve the following result:

departments: {
  dep_name: string,
  globalObj: {
    count: number[],
    admin: {
      department: string,
      email: string,
      img_path: string,
      name: string
    }[]
  }
}[];

In simpler terms, I want each department name to correspond with its respective globalObj.

However, I am unsure of how to go about merging them accurately.

Your help and guidance on this matter would be greatly appreciated.

Thank you!

Answer №1

It's a little unclear what you're referring to

I understand that you're talking about getting the corresponding global object

If you want to merge an array with the same global object, you can use the code below:

let globalObject = {
  count: [1,2,3],
  admin: [
    {
        department: 'a',
        email: 'b',
        img_path: 'c',
        name: 'd'
    }
  ]
}

let departmentNames = ["x", "y", "z"];

let mergedArray = departmentNames.map((depName) =>
{
    return {
        dep_name: depName,
        globalObj: globalObject
    }
})

Answer №2

If you want to update the secondResponse JSON, all you have to do is add a key to the object.

Just follow this example:

var firstResponse = {
    globalObj: {
        count: [],
        admin: {
            department: '',
            email: '',
            img_path: '',
            name: ''
        }
    }
}

var secondResponse = {
    dep_name: ''
}   

secondResponse.globalObj = firstResponse;

By doing this, you will get an updated version of the secondResponse JSON.

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

Guide on displaying the marker location on a map when hovering over a div element, similar to the method used by AirBnb

In the left side div of my page, there are items such as images, titles, details, and addresses. On the right side, I have a Leaflet Map that shows markers of these addresses taken from the left side items. What I want is to display the marker locations on ...

Encrypt JavaScript for a jade layout

I need to find a way to successfully pass a .js file to a jade template in order for it to display correctly within an ACE editor. However, I am encountering errors when attempting to render certain files that may contain regex and escaped characters. How ...

Update the display immediately upon a change in the state

In my app.js file, the code looks like this: export const App = () => { const [selectedMeals, setSelectedMeals] = useState<string[]>(["allItems"]); const onCheckHandler = (e: any) => { const checkedValue = e.target.value; if (e.targ ...

Learn how to extract values from an object in Vue JS time-slots-generator and display either PM or AM based on the

Using the time-slots-generator package, I am able to display the time from 0:15 to 24:00. However, the issue is that this package does not have built-in functionality to display AM/PM, so I had to create a manual solution for it. To achieve this, I modifi ...

Methods for establishing state within a React Native render function

I encountered an issue when attempting to set state within the render lifecycle. Warning: It is not recommended to update state during an ongoing state transition, such as in the render method or another component's constructor. The render method s ...

Angular xeditable encounters difficulties when updating the local model

In the process of designing a form, I am looking to establish a relationship where the value in one text field is dependent on another textbox. Referring to angularjs, xeditable typically updates the local model after clicking save. However, my goal is to ...

Is there a way to display the specific information of a flatlist item in a pop-up window?

Welcome to the HomesScreen.js! This section handles rendering the flat list elements. import { StatusBar } from 'expo-status-bar'; import { Button, Image, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import { ...

Displaying content in a hidden div on click event

I am part of a volunteer group for prostate cancer awareness and support, and our website features multiple YouTube videos that are embedded. However, the page has been experiencing slow loading times due to the number of videos, despite them being hidden ...

ReactJS not displaying the class effect as intended

When using the react zoom pan pinch library, I am trying to set the height to "100%" for TransformWrapper and TransformComponent. Interestingly, it works perfectly fine when done through Chrome inspect, but when attempting to add a className or use style={ ...

no output upon completion of a class constructor - JavaScript

I am facing a perplexing issue with my code. Let me break it down for you: class Block{ constructor(timeStamp, lastBlockHash, thisBlockData, thisBlockHash){ this.timeStamp = timeStamp; this.lastBlockHash = lastBlockHash; this.t ...

Disrupting methods on a dependency within QUnit can cause tests against that dependency to fail

Currently, in my Google Apps Script project, I am unit-testing an application using QUnit for test-driven development purposes. Code Under Test The function I am currently focusing on testing and developing is the creation of a Sheet from a long string o ...

Stop YouTube Video in SlickJS Carousel, Remove Placeholder Image Forever

Feel free to check out the CodePen example: http://codepen.io/frankDraws/pen/RWgBBw Overview: This CodePen features an ad with a video carousel that utilizes SlickJS. There are a total of 3 YouTube videos included in the carousel, with the SlickJS ' ...

Unpredictable order of replies retrieved using $http.get

I am struggling to create a function that sends multiple requests to the server based on the number of Ids in the idArray. The issue I am encountering is that the data being pushed into the dataArray does not align with the corresponding Ids of the idArr ...

Can you point me towards the location of Sigma.js' sigma.utils.xhr() function?

I came across a peculiar issue with lines 23 and 24 of sigma/plugins/sigma.neo4j.cypher/sigma.neo4j.cypher.js: sigma.neo4j.send = function(neo4j, endpoint, method, data, callback) { var xhr = sigma.utils.xhr(), Surprisingly, sigma/src/utils/sigma.uti ...

Exploring the possibilities of integrating jQuery into Firefox extensions

Can someone provide guidance on effectively implementing jQuery within a Firefox extension? My research has not yielded any up-to-date methods that address the latest version of jQuery, and I am aware that directly including it via script tag may lead to c ...

Different Methods of Joining Tables in SQLike

Struggling with creating a two-level JOIN in SQLike, currently stuck at the one level JOIN. The source tables are JSONs: var placesJSON=[{"id":"173","name":"England","type":"SUBCTRY"},{"id":"580","name":"Great Britain","type":"CTRY"},{"id":"821","name":" ...

Decline the input according to the percentage

After experimenting with the script, I discovered that it did not perform as expected (even though it works on Google Webapp's script HTML form). My goal is to invalidate an input if the Downpayment is less than 30% or more than 100% of the Price, in ...

Utilizing Jade to access and iterate through arrays nested in JSON data

Take a look at this JSON data: { "Meals": { "title": "All the meals", "lunch": ["Turkey Sandwich", "Chicken Quesadilla", "Hamburger and Fries"] } } I want to pass the array from this JSON into a jade view so that I can iterate over each item in ...

When implementing javascript_pack_tag in Rails, an EOFError may occur

It seems like the files in public/packs/js are having trouble loading. Here are the javascript tags being used in the view: = javascript_include_tag 'application' = javascript_pack_tag 'application' The error displayed in the browser ...

How can you pass arguments between commands in discord.js?

I need to transfer arguments; I have attempted to make them global variables, but I am unsure about the correct approach. Command using the arguments : let messageArray = message.content.split(" "); const args = messageArray.slice(1); const invi ...