Move all the attributes from one object stored in an array to another object within the same array using JavaScript or TypeScript

Is there a more efficient way to copy or move properties from one object within an array to another object? I've devised a simple logic that works, but I'm confident there must be a better approach. Can anyone offer some advice?

var first =  [
    {
        "AGREE_EFF_DATE__0": "02-Aug-2018",
        "AGREE_TERM_DATE__0": "30-Apr-2021",
        "AGREE_IND__0": "P1",
        "P_DBAR_IND__0": "N",
        "AGREE_EFF_DATE__1": "01-May-2021",
        "AGREE_TERM_DATE__1": null,
        "AGREE_IND__1": "NP",
        "P_DBAR_IND__1": "N",
        "PROVIDER_SPECIALITY__0": "PSYCHOLOGY, CLINICAL",
        "PROVIDER_SPECIALITY_CODE__0": "CK"
    }
];
var second = [
    {
        "STATUS": "ACTIVE",
        "MEDICARE_NUMBER" : 12345
    }
];

for(let i = 0; i < second.length; i++) {
    
    var first_keys = Object.keys(first[i]);
    var first_values = Object.values(first[i]);
    
    for(let j = 0; j < first_keys.length; j++) {
        second[i][first_keys[j]] = first_values[j];
    }
}


console.log(second);

//Output-
[
  {
    STATUS: 'ACTIVE',
    MEDICARE_NUMBER: 12345,
    AGREE_EFF_DATE__0: '02-Aug-2018',
    AGREE_TERM_DATE__0: '30-Apr-2021',
    AGREE_IND__0: 'P1',
    P_DBAR_IND__0: 'N',
    AGREE_EFF_DATE__1: '01-May-2021',
    AGREE_TERM_DATE__1: null,
    AGREE_IND__1: 'NP',
    P_DBAR_IND__1: 'N',
    PROVIDER_SPECIALITY__0: 'PSYCHOLOGY, CLINICAL',
    PROVIDER_SPECIALITY_CODE__0: 'CK'
  }
]

Answer №1

It is generally recommended to use iteration methods like arr.map(), arr.forEach(), or arr.reduce() over manually indexed loops.

An efficient way to merge objects is by using object spread functionality.

Combining these techniques, you can simplify the logic to:

const result = first.map((firstObj, i) => ({ ...firstObj, ...second[i] }))

In this approach, we are iterating over each element of the 'first' array using map() and creating a new array based on the function's result, which merges corresponding elements from the 'second' array.

The final step involves expanding both objects into a new object to generate the desired result.

var first =  [
    { a: 1, b: 2 },
    { a: 4, b: 5 },
];
var second = [
    { c: 3 },
    { c: 6 },
];

const result = first.map((firstObj, i) => ({ ...firstObj, ...second[i] }))

console.log(result)

This code snippet is also valid in TypeScript.


NOTE: One key distinction between my implementation and yours is that your code modifies the objects in 'second', whereas mine creates new objects without altering the original contents of 'second'.

Choosing between the two approaches depends on how the output is utilized and how data flows within your application.

Answer №2

When working with iteration, it's important to be cautious as the number of elements in the first and second arrays may differ. One possible approach to address this issue is outlined below:

const firstArr = [
    {
        "AGREE_EFF_DATE__0": "02-Aug-2018",
        "AGREE_TERM_DATE__0": "30-Apr-2021",
        "AGREE_IND__0": "P1",
        "P_DBAR_IND__0": "N",
        "AGREE_EFF_DATE__1": "01-May-2021",
        "AGREE_TERM_DATE__1": null,
        "AGREE_IND__1": "NP",
        "P_DBAR_IND__1": "N",
        "PROVIDER_SPECIALITY__0": "PSYCHOLOGY, CLINICAL",
        "PROVIDER_SPECIALITY_CODE__0": "CK"
    }
];
const secondArr = [
    {
        "STATUS": "ACTIVE",
        "MEDICARE_NUMBER": 12345
    }
];

console.log(mergeArrays(firstArr, secondArr));

function mergeArrays(arr1, arr2) {
    const resultArr = [];
    const minLen = arr1.length < arr2.length ? arr1.length : arr2.length;

    for (let i = 0; i < minLen; i++) {
        resultArr.push({...arr1[i], ...arr2[i]});
    }

    return resultArr;
}

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

Click the button to save the text to your clipboard with a customized

Can anyone suggest a method for duplicating div text using JavaScript while preserving the style attributes (italics, font family, size, etc.)? My goal is to paste the copied text into Word and have it maintain the same appearance as on the webpage. For e ...

What is the best approach for managing this type of printing in Java?

When printing the string "The winner is student 1 student 2 student 4 student 5 with points 20", I want the output to be "The winner is student 5 with points 20." If more than one student has the same score, the desired output should be "The winner is stu ...

Issues with navigation in React Native Typescript

Currently, I am in the process of developing a new React Native Expo project utilizing TypeScript. I have been attempting to configure navigation following the guidance provided in React Native's TypeScript documentation. However, upon running and sim ...

Steps to prevent closing the alert box when clicking outside of it in Ionic

I am currently developing an Ionic 2 app and I have implemented the following component: http://ionicframework.com/docs/components/#alert import { AlertController } from 'ionic-angular'; export class MyPage { constructor(public alertCtrl: Al ...

Tips for utilizing the nth-child selector to exclude hidden divs

I am facing an issue with displaying random blocks in rows. Each time a block falls into a new row, I want it to have a different style. However, when the user clicks on a button to hide certain blocks using display:none, the problem arises because the nth ...

Safari has trouble with AJAX cross-origin requests, while Chrome and Firefox handle them without issue

I am developing a Shopify app that utilizes script tags and requires an ajax call to our server to retrieve necessary information about the shop. While everything seemed to be functioning correctly, my colleague pointed out that it was not working on his i ...

create an HTML element using JavaScript to display a box with dimensions of n

I am attempting to create a grid in an HTML document using only plain JavaScript. The idea is to take a number from a URL and use that as the basis for generating the grid. For example, if my URL looks like this: abc.html?num=5, then I would need to creat ...

Opacity error with jQuery slider specifically affecting Google Chrome browser

My Magento site features a custom-built slider that is both responsive and has unique touch behavior. The desired behavior for the slider is as follows: A three-image slider where the middle image has an opacity of 1.0, while the other two images have an ...

Validating an object's schema using AJV when there are unknown properties present

Within my platform, there is an amusing scenario that I find to be the most effective. I am currently attempting to validate a JSON Schema where an object contains unknown keys with a consistent schema as their values. Each key represents a unique ID and h ...

Having trouble retrieving the updated useState variable outside of useEffect in React Hooks?

Recently, I dove into the world of React and started developing a React app that allows users to drag food items to an order list using React DND. However, I encountered a problem where I couldn't access the updated OrderList variable outside the useE ...

Forcing the Empty Table message in jQuery DataTables post an AJAX request

My configuration for jquery-datatables includes a custom search filter that acts as both the standard keyword filter and a specific Item ID search using an ajax call to retrieve a value from the back end, which is then used to search a particular column in ...

Showcase pictures from a directory in real-time using a combination of jQuery and Bootstrap as the folder continues to fill up with images

Although I am just beginning to learn about UI, I have a question that seems important to me. In my application, there is a background thread that downloads images and saves them in a folder named "images". I want these images to be displayed in the UI as ...

Tips for retaining a chosen selection in a dropdown box using AngularJS

How can I store the selected color value from a dropdown box into the $scope.color variable? Index.html: <label class="item item-select" name="selectName"> <span class="input-label">Choose your favorite color:</span> <select id="colo ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

Deactivating toolbar in material table in ReactJS while maintaining default functionalities

https://i.sstatic.net/XrA3I.pngHow can I remove the toolbar to eliminate the blank space between the table and button without disabling the add new row functionality? <MaterialTable title=" " options={{ ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

Trapped in the JavaScript Checkbox Filter Maze

After successfully creating a javascript-only filter, I have hit a roadblock and could really use some assistance. The filter is divided into "days" and "events". When a user clicks on a day or multiple days, the events for those selected days are displa ...

What could be the reason for the failure of .simulate("mouseover") in a Jest / Enzyme test?

I have a scenario where a material-ui ListItem triggers the display of a material-ui Popper containing another ListItem on mouse over using the onMouseOver event. While this functionality works as expected, I am facing difficulties replicating the behavior ...

Create a dynamic slideshow using a bootstrap carousel in conjunction with the powerful php glob() function

I'm struggling to create a homepage featuring a slider that pulls images dynamically from a subfolder within the Wordpress uploads directory. Here's my code: <div id="" class="carousel slide" data-ride="carousel"> <!-- Wrapper for sl ...

Issue with negative z-index in modal window has not been resolved

I'm currently trying to customize the radio button using my own CSS styles, but I've encountered an issue. For some reason, setting the z-index to -1 is not working when the radio button is within a modal. Below is the code snippet that I am wor ...