Merge the contents of the second nested array of objects with the first nested array of objects

How can I transfer key values from an array of objects to another array object?

I want to assign the key:value pair from one array of objects to another existing array of objects.

I've looked at this link, but it doesn't seem to work in my situation.

My attempt did not produce the desired output that I'm aiming for.

const DataA = {
  "id": 57,
  "status": true,
  "options": [{ "id": 1, "name": "Type A" },
    { "id": 2, "name": "Type B" },
    { "id": 3, "name": "Type C" }]
}

const DataB = {
  "id": 57,
  "status": true,
  "options": [{ "id": 1, "value": 10 },
    { "id": 2, "value": 20 },
    { "id": 3, "value": 30 }]
}

let result;
var A1 = DataA.options.map((v) => {
  console.log(v);
  result = v;
})

var A2 = DataB.options.map(v => {
  result.options = v;
  console.log("result",result);
})

let arr3 = DataA.options.map((item, i) => Object.assign({}, item, DataB[i]));

console.log(arr3);

The desired result should look like this:

const DataA = {
  "id": 57,
  "status": true,
  "options": [{ "id": 1, "name": "Type A", "value": 10 },
    { "id": 2, "name": "Type B", "value": 20 },
    { "id": 3, "name": "Type C", "value": 30 }]
}

I need to merge a deep clone of the array which is slightly different from what's discussed in this forum.

Answer №1

The referenced duplicate actually provides a solution to your query, but it is important to tailor it to your specific scenario rather than simply copying and pasting.

DataA.options = DataA.options.map((item, i) => Object.assign({}, item, DataB.options[i]));

However, considering that this modifies the original DataA object directly, it might be more efficient to utilize forEach() instead of creating an additional array with .map().

DataA.options.forEach((item, i) => Object.assign(item, DataB.options[i]));

Both methods mentioned above assume that the options arrays in both objects are a. of equal length, and b. arranged by id. To eliminate these assumptions, you can employ .find() to search for corresponding elements instead of relying on index positions.

DataA.options.forEach(item =>
  Object.assign(item, DataB.options.find(({ id }) => id === item.id)));

const DataA = {
  "id": 57,
  "status": true,
  "options": [
    { "id": 1, "name": "Type A" },
    { "id": 2, "name": "Type B" },
    { "id": 3, "name": "Type C" }]
}

const DataB = {
  "id": 57,
  "status": true,
  "options": [
    { "id": 1, "value": 10 },
    { "id": 2, "value": 20 },
    { "id": 3, "value": 30 }]
}

DataA.options.forEach(item =>
  Object.assign(item, DataB.options.find(({ id }) => id === item.id)));

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

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

Enhanced Bootstrap 4 Navigation Bar Lofty on Tablet Display with Divided Functionality

Currently, I am utilizing Bootstrap 4 for my personal website; however, I have encountered an issue on my tablet where the top menu is divided into two lines: The top row displays the "font awesome" icon Directly below each icon are the section names co ...

What is the process for incorporating custom controls into the Mantine Embla Carousel within a Next.js environment?

Check out this code snippet: import React from "react"; import { Container } from "@mantine/core"; import { Carousel } from "@mantine/carousel"; import { ArticleCard } from "@/components"; import { cards } from " ...

Meteor: accounts-ui Package - Simplifying User Authentication in Your

I am interested in implementing the accounts-ui package to handle account management within my application. However, the current sign-in form appears as a drop-down menu. Is there a way to encapsulate it within a button so that clicking on the button wil ...

Incorrect footer navigation on my Vuepress website

I'm in the process of developing a vuepress single page application for showcasing and providing downloads of my personal game projects. When it comes to website navigation, I am aiming to utilize the native sidebar exclusively. This sidebar will hav ...

Differentiate various collections of shapes

My application has a specific workflow: 1) Next to the name of Patient X, there is a "Check In" button. Once clicked, this action is recorded on the server side. 2) Upon clicking the "Check In" button, a dropdown menu appears with various locations for t ...

Issues arise when attempting to make a SOAP request in NodeJS, as opposed to PHP where it functions seamlessly

As I work on integrating a SOAP-API to access data, I encounter an error when trying to implement it in my ExpressJS-Service using NodeJS. The API documentation provides examples in PHP, which is not my preferred language. My PHP implementation works flawl ...

Recursively toggle child elements using JQuery

My knowledge of JQuery is limited, so here's the issue I'm facing. Below is an example of the HTML structure: <ul class="first-class"> <li class="second-class"> <a href="#_"> <i class="fa fa-plus"></i& ...

What is the process for altering the color of an HTML output depending on its values?

I created a simple HTML code to showcase some outcomes. The possible results are SUCCESS, Failure, and Still Failing. I want these results to be displayed with corresponding colors, such as green for SUCCESS, and red for both Failure and Still Failing. I ...

What is the reasoning behind storing type definitions in the @types namespace within npm?

Have you ever wondered why type definitions in npm are stored under the @types namespace which isn't directly linked to a specific organization, user, or library? Wouldn't it make more sense for npm libraries to have their types located under @[o ...

Express server encounters crash due to duplicate registration

I am currently running a node server with an API endpoint that crashes whenever a duplicate email is entered using Postman. The server runs smoothly without any issues when a non-duplicate registration occurs. However, if a duplicate email is submitted, I ...

Building a matrix-esque table using d3.js reminiscent of HTML tables

I would like to generate a table resembling a matrix without numerical values. 1. Here is an example of my database table: | CODE | STIL | SUBSTIL | PRODUS | |------|-------|----------|---------| | R | stil1 | substil1 | produs1 | | R | stil1 | s ...

Subscribing with multiple parameters in RxJS

I am facing a dilemma with two observables that I need to combine and use in subscribe, where I want the flexibility to either use both arguments or only one. I have experimented with .ForkJoin, .merge, .concat but haven't been able to achieve the des ...

`Trying to Implement jQuery Function with No Success`

My webpage includes the following HTML code: <div class="new-nav"> </div> Below is my jQuery script: var div1 = " <div class=\"metro-nav-block nav-block-orange\">\n <a data-original-t ...

Errors found during compilation when running the npm start command

After choosing to develop an app with React using VS Code, I initiated the process by running npm create-react-app ./, which was a success. However, when I proceeded to execute the command npm start, it resulted in compilation errors related to files suc ...

`Node.js: Implementing intricate routes with Express`

Just starting out with Node.js and Express here. I have a question about setting up routes in Express.js. In my project, I need to match the following URL: example.com/?campaign=123&click=123. I've tried using the following condition in the app ...

How can we bring in a function into a Vue component?

I'm currently facing an issue with importing a single function into my Vue component. To tackle this problem, I separated the function into its own js file: randomId.js: exports.randomId = () => //My function ... Within my Vue component, I attem ...

Creating a div anchor tag within a component in React

Forgive me if this question has already made its rounds on the internet, but I can't seem to get anything to work in my favor. I was under the assumption that all you had to do was append the # + div id at the end of a URL to navigate to a specific d ...

Error: Cannot iterate over Redux props map as it is not a function

I've encountered an issue while trying to render out a Redux state by mapping through an array of objects. Despite receiving the props successfully, I keep getting an error stating that 'map is not a function'. It seems like the mapping func ...

"Stopping the default behavior of an event can impact the remainder of the code

Within this project, there exist three .ejs pages, namely index.ejs, loading.ejs, and result.ejs. The initial page to load is index.ejs, which contains the following code within its script tag: document.addEventListener("DOMContentLoaded", functi ...