Combining two arrays of objects with unique properties into one

Two arrays of objects are given:

array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
        array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];
    

The goal is to merge them in a way that each object contains properties from both arrays, excluding the object not present in the first array.

An attempt has been made using the following code snippet:


                var mergeArrays = function() {
                    var array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
                    var array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];

                    var newArray = array2.filter(i => array1.map(a=> { if(a.id == i.id) i.qty = a.qty; return i; }));

                    return newArray.filter(i=> { if(i.qty) return i; });
                }

                console.log(mergeArrays());
            

While this method works in some cases, there are inconsistencies depending on the environment. Seeking alternative solutions to address this issue.

Answer №1

To enhance the first array by incorporating properties from the second array, you can reference objects in the second array and map them to the first.

const
    array1 = [{ id: 1, cost: 200, qty: 56 }, { id: 2, cost: 100, qty: 16 }],
    array2 = [{ id: 1, cost: 200, desc: "a good one" }, { id: 2, cost: 100, desc: "a bad one" }, { id: 3, cost: 50, desc: "an okay one" }],
    references2 = Object.fromEntries(array2.map(o => [o.id, o])),
    result = array1.map(o => ({ ...o, ...references2[o.id] }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

const data = [
  {"id":1,"price":200,"quantity":56},
  {"id":2,"price":100,"quantity":16}
];

const details = [
  {"id":1,"price":200,"description":"a good one"},
  {"id":2,"price":100,"description":"a bad one"},
  {"id":3,"price":50,"description":"an okay one"}
];

const result = data.reduce((prev, current) => {
  const matchingObj = details.find(item => item.id === current.id) ?? {};
  prev.push({...current, ...matchingObj});
  return prev;
}, []);

console.log(result);

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

Error code 400 encountered when processing Stripe webhooks

I've been working on integrating stripe webhooks into my node.js/express application, but I keep running into a 400 response from the stripe cli. Even though I followed the documentation closely and ensured that the secret key for the webhook is corre ...

IFrame issue: Page is constantly refreshing when on iframe source

Recently, I started working with asp.net and I'm attempting to call an Iframe src within a table row using a JavaScript click event. (i.e onclick="return loadPhaseWiseChart("DGSET00025");") Here is my code snippet: <tr height="25" id="row3" oncli ...

Issue with setting a cookie using Node.js Puppeteer: cookie not being set as expected

I'm facing an issue with setting a specific cookie in the browser using Puppeteer. After executing the code to set the cookie and then displaying all the cookies on the page through console.log, the new cookie is not visible. The code I am running is ...

Using Json.stringify enables the conversion of HTML elements into a JSON

Currently attempting to transmit data from an MVC view to a controller with request validation enabled for the application. However, when attempting to send values containing HTML tags to the controller, no exceptions are being thrown. Below is the AJAX ...

jQuery Algorithm for calculating totals

Here is an algorithm for formatting amounts using jQuery: Visit jsfiddle for the code However, there are some issues. For instance, if I enter 900.800,00 and then delete the "9", it still displays 00.800,00. How can this be resolved? I have fixed severa ...

Java Array Iteration in a Loop

In my scenario, I have an array of objects that are all instances of the class 'Person'. Each Person object contains attributes - a String name and an Array scores. The task at hand involves processing a text file which holds the scores of each p ...

Fix background transition and add background dim effect on hover - check out the fiddle!

I'm facing a challenging situation here. I have a container with a background image, and inside it, there are 3 small circles. My goal is to make the background image zoom in when I hover over it, and dim the background image when I hover over any of ...

Retrieve the specific element value located at an index within an array in PHP

I came across a coding issue that I need assistance with. My task is to output only the values of specific indexes in an array. Below is the code that I have implemented: <?php $str = 'test1:val1,test2:val2,test3:val3' $ex1 = explode(' ...

Leveraging Vue.js to showcase API information through attribute binding

My application is designed to allow a user to select a Person, and then Vue makes an API call for that user's posts. Each post has its own set of comments sourced from here. You can view the codepen here Here is my HTML structure: <script src="h ...

What is preventing me from generating a string for transform:translate within Angular.js?

Attempting a new approach here $scope.graph.transform = "transform: translate(" + $scope.graph.width + "," + $scope.graph.height + ");"; Despite my efforts <h3>transform: <span ng-bind="grap ...

Tips for avoiding variable overwriting while utilizing it in a for loop to color objects

I am looking to enhance the efficiency of my function in creating HTML objects using native JS script. The current function paints text, but I want it to optimize. When running the function, I expect different iterations of text to be written in HTML thro ...

Toggle between multiple chart displays within a <div> using a selection list

With around 20 div sections on my webpage, I encountered an issue where selecting option 1 and then 2 still displayed the chart of 1. Any tips on adjusting the JavaScript to ensure that charts are displayed correctly when changing selections in the list? W ...

Creating Input Fields on the Fly in VueJS

My goal is to dynamically manipulate input fields in real-time. I found a helpful solution at , which successfully adds and removes fields as needed. However, when attempting to save the input values to the database, the functionality breaks. Here is the ...

Verify if there are DOM elements located within a DIV container, execute the functions associated with those elements sequentially

I am in the process of creating a game using HTML, CSS, and JavaScript. My focus right now is on manipulating DOM elements without relying on the canvas tag. The goal is to develop a pseudo graphical programming language, similar to the environment provide ...

Navigating Dynamically between tabs - A How-to Guide

I am working on a mat-tab Angular app where I need to dynamically generate links and transfer them to a navLinks object. Despite ensuring that the concatenation is correct, it seems like my approach is not working as expected. Here's a glimpse of what ...

Encountering a Forbidden Error with Superagent

Here is the content of my index.js file I am attempting to fetch a response from a sports data API. I can successfully send curl requests to it, but when trying this method, I encounter a 403 forbidden error. var express = require('express'); v ...

What is the best way to reset local state after triggering a success action in Redux Saga?

I'm looking to reset my component state after a successful call in redux saga. Is there a way to achieve this? Currently, I am using the component state to track my input value. this.state = { department: '', }; The solution I have im ...

a guide on expanding a submenu in a shiny dashboard sidebar without using automated functions

I am facing a challenge in manually expanding a submenu within a sidebar on shiny dashboard. The function updateTabItems does not seem to work with nested menus, only with normal menus. For example, when I click on 'Switch tab', it switches the ...

Optimizing nested collections with JavaScript arrays of boolean values

I have multiple nested collections of JavaScript objects and I believe there has to be a more efficient way to achieve what I'm doing. The goal is to access the values of the fields in Objects 1, 2, and 3 and check if they are true or false. Below is ...