Transfer a single property from a particular object in one array to another array of objects based on a condition (JavaScript ES6)

I have 2 sets of data arrays coming from 2 separate API calls

const data1 = [
  {
    name: 'John',
    age: 30,
    id: 1,
  },
  {
    name: 'Sarah',
    age: 28,
    id: 2,
  },
];

const data2 = [
  {
    status: 'active',
    interest: "photography",
    id: 1,
  },
  {
    status: 'inactive',
    interest: "traveling",
    id: 2,
  },
];

This is the current method I am using, but it combines the entire object from data2 to data1 if their ids match

const mergedData = data2.reduce((accumulator, current) => {
    accumulator[current.id] = current;
    return accumulator;
  }, {});

  const updatedData = data1.map((d) =>
    Object.assign(d, mergedData[d.id]) 
  );

The resulting combined data is:

{
    name: 'John',
    age: 30,
    id: 1,
status: "active",
interest: "photography"
  },
  {
    name: 'Sarah',
    age: 28,
    id: 2,
status: "inactive",
interest: "traveling"
  },

I want to transfer only the status property from the second set of data arrays into the first set where the objects' ids match

Expected outcome:

const newData = [
      {
        name: 'John',
        age: 30,
        id: 1,
        status: "active"
      },
      {
        name: 'Sarah',
        age: 28,
        id: 2,
        status: "inactive"
      },
    ];

Answer №1

If you want to create a new array, you can utilize the map function and use find to locate any warning that matches the corresponding id:

let data1 = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 35 }
];

let data2 = [
  { id: 1, occupation: 'Engineer', alert: 'Low' },
  { id: 2, occupation: 'Designer', alert: 'Medium' },
  { id: 3, occupation: 'Developer', alert: 'High' }
];

let getWarnings = (data, warningsArr) => data.map(item => {
  
  let match = warningsArr.find(warn => warn.id === item.id);
  
  return { ...item, ...(match ? { alert: match.alert } : {}) };
  
});
console.log(getWarnings(data1, data2));

Consider structuring your data with id mappings for better organization:

let data1 = {
  id1: { name: 'Alice', age: 25 },
  id2: { name: 'Bob', age: 30 },
  .
  .
  .
}

let data2 = {
  id1: { occupation: 'Engineer', alert: 'Low' },
  id2: { occupation: 'Designer', alert: 'Medium' },
  .
  .
  .
}

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

hiding form fields using javascript

As a beginner in javascript, I am facing a challenge with a set of checkboxes in an HTML form. These checkboxes are generated dynamically from a python script. Among them, there is a checkbox labeled "N/A" that I want to hide automatically when any other c ...

How can we use the jQuery each loop to iterate through a JSON object, compare values to another object, and ensure that no duplicate prints occur?

Hey everyone! I'm currently working on a music player and I'm utilizing JSON to store my ID3, also known as "MP3 Metadata". The issue I'm facing is that I'm extracting an object and trying to compare the values to avoid repeating the sa ...

Is it necessary to append the path with __dirname when utilizing Node's fs.readFile()?

Illustration: fs.readFile(path.join(__dirname, 'path/to/file'), callback); compared to fs.readFile('path/to/file', callback); Both methods appear to function properly, prompting me to inquire whether I can omit the __dirname prefix, ...

Learn the steps to create a 3D carousel that spins on its own without the need for manual clicks and pauses once the

Looking for a solution to create a 3D carousel that rotates continuously without the need for buttons to be clicked, and pauses when the mouse hovers over it, then resumes rotation when the mouse is not hovering over it. var carousel = $(".carousel"), ...

Transferring data from PHP to AJAX and then injecting it into an SQL query

I've been attempting to pass a datepicker variable into an onclick ajax function, which then sends it to another ajax method that passes the variable to an SQL query. The result of the query is then passed back into the ajax function to generate a cha ...

The function `collect` cannot be found for the object #<Page:0x007f4f200a9350

Seeking assistance with an error I've encountered. As a novice, I'm still navigating my way through this, so any guidance on how to resolve it would be greatly appreciated. Attached is the portion of code that is triggering the error: 3: <%= ...

Establish a JavaScript hyperlink to assign a value to a shared rendering parameter

In my attempt to create a JavaScript link that, when clicked, assigns a value to a public render parameter in WebSphere Portal, I'm encountering unexpected code instead of the intended value. Here is how I am constructing the link using JavaScript: ...

Converting floating point numbers to fixed floating point numbers in JavaScript

Consider this scenario: I need to calculate 3 divided by 6, which equals 0.5 as a floating number. However, when I used the javascript toFixed(6) method to round it to 6 decimal points, it returned '0.500000' as a string instead of a floating num ...

Consolidate and then transfer to a different database

How can I insert the data returned from my aggregate (controller function) into another collection called User? Here is the schema for the User: const userSchema = new mongoose.Schema({ firstName: { type: String, required: [true, &ap ...

Enhancing user experience with jquery autocomplete matching

Currently utilizing the JQuery Autocomplete plugin. It seems that the default behavior is to match from the start, so "foo" matches "fool", but not "bufoon". I am seeking a way for matching to happen anywhere in the text and also in a case-insensitive man ...

A guide to calculating the sum of columns using TypeScript and integrating it with Angular 8

Currently, I am attempting to calculate the average of all columns and display it at the footer of my table. The table data is fetched from an API resulting in a structure like this: <tr *ngFor="let item of items"> <td>{{item.num1 ...

Is there a way to remove array elements once in order to replace them with new ones using a for loop?

My objective is to achieve the following: Assign an array value (list) to another array (options). If the user input (searchVal) matches a value in the list, remove existing options and add this match. Subsequently continue adding any additional matches w ...

Tips for recognizing a specific object ID within an array in order to modify the status of an element within that object

My goal is to accurately identify a specific panel within an expanded array and link that panel's ID to a button, while also ensuring the button is disabled when no panels are expanded or more than one panel is expanded. However, I am encountering iss ...

Is it possible to open a new tab by clicking on an anchor tag

I have a scenario with two tabs on a webpage, each with anchor tags that I can navigate to from the homepage using a header menu item anchor. The tabs are working fine with an active class and aria-expanded="true", but I'm facing an issue where the ap ...

Having trouble with Angular's ng-tags-input? Are you getting the error message "angular is not defined"? Let

I recently created a new Angular project using the following command: ng new "app-name" Now, I'm attempting to incorporate ngTagsInput for a tag input feature. However, every time I try to build and run my app, I encounter an error in my browser con ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

Matrix calculation for bone orientation towards an object in Three.js

I am encountering issues with calculating the orientation of a bone to "look at" an object. The lookAt function is not functioning as expected for me. This could be due to the fact that the bone's matrix is an identity matrix in local space, so the de ...

Embracing the node mindset with a Java foundation

As a Java Developer, I have become accustomed to working in a sequential manner where tasks are executed one after the other or concurrently with multiple threads. The organization of code in a sequential way seemed logical under this paradigm. However, wh ...

What are the steps to set a 404 status code in next.js when utilizing ISR with a fallback of "blocking"?

When a route does not match, what is the best way to redirect to a 404 error page and ensure that the status code is displayed as 404 in the network tab using ISR with fallback: "blocking"? ...

Issue finding a route based on dates

Hey everyone, I'm working on a feature where I need to fetch tasks made by a user within a specific date range provided by the user. However, I am facing some issues with getting the date and routing it. Here is the URL format that I am trying to work ...