Modify the values of an array of objects using a separate array

const array1 = [
  {
    id: "40",
    alias: "Number",
    name: "Number",
  },
  {
    id: "41",
    alias: "Salary",
    name: "Salary",
  },
];


const array2 = [
  {
    id: "Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__",
    name: "Salary",
  },
  { id: "40", name: "Number" },
];

I am looking to update the 'Salary' identifier in array2 to be "41" instead of "Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__"

This is the code snippet I've attempted:

const result = array1
  .filter((array1Value) =>
    [...array2].find(
      (array2Value) => array2Value.name === array1Value.alias
    )
  )
  .map((column) => ({
    id: column.id,
    name: column.name,
  }));
console.log("result: ", result);

The above code works well, but it creates a new set of arrays using map. Is there a more efficient way to replace the values directly without creating a new array set? Open to suggestions for a better approach.

Answer №1

Here is a solution that utilizes the `forEach` and `find` high-order functions:

const array1 = [
  {
    id: "40",
    alias: "Number",
    name: "Number",
  },
  {
    id: "41",
    alias: "Salary",
    name: "Salary",
  },
];

const array2 = [
  {
    id: "Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__",
    name: "Salary",
  },
  { id: "40", name: "Number" },
];

array1.forEach((item1) => {
  const matchingItem = array2.find((item2) => item2.name === item1.alias);
  if (matchingItem) {
    matchingItem.id = item1.id;
  }
});

console.log("Updated array2:", array2);

Answer №2

You can implement the use of the forEach method for this task:

array2.forEach(data2 => {
    array1.forEach(data1 => {
        if (data2.name == data1.alias) data2.id = data1.id;
    })
})

const array1 = [{
    id: "40",
    alias: "Number",
    name: "Number",
  },
  {
    id: "41",
    alias: "Salary",
    name: "Salary",
}];

const array2 = [{
    id: "Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__",
    name: "Salary",
  },
  {
    id: "40",
    name: "Number"
  },
];

console.log("Initial values:");
console.log(array2);

array2.forEach(data2 => {
  array1.forEach(data1 => {
    if (data2.name == data1.alias) data2.id = data1.id;
  })
});

console.log("Updated values:");
console.log(array2);

Answer №3

When condensed into a single line of code:

a2.forEach(x => x.id = a1.find((y) => x.name===y.name)?.id ?? x.id);

const dataSetOne = [{
    id: "40",
    alias: "Number",
    name: "Number",
  },
  {
    id: "41",
    alias: "Salary",
    name: "Salary",
  },
];


const dataSetTwo = [{
    id: "Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__",
    name: "Salary",
  },
  {
    id: "40",
    name: "Number"
  },
];

dataSetTwo.forEach(x => x.id = dataSetOne.find((y) => x.name===y.name)?.id ?? x.id);

console.log(dataSetTwo);

Answer №4

let copy = JSON.parse(JSON.stringify(arr2));
arr2.forEach((element, idx) => {
    console.log(element?.name);
    for (let val of arr1) {
        if (val.name === element.name && val.id !== element.id) {
            copy[idx]['id'] = val.id;
        }
    }
});
console.log(copy);

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

Struggling to get CORS request to function properly

I am encountering a CORS issue while trying to retrieve data from a webservice on a different domain. Within my controller, I have the following code: $http({method: 'GET', url : 'http://somewebserviceapi.com?idAppli=' + appId, header ...

Bootstrap encountered an issue with altering header information

I've been trying to set up a notification system that plays a sound every time someone makes a new post. I'm working with Bootstrap 4 and I've tried inserting JavaScript into the functions page, but no matter how many times I call the ' ...

Using React to insert a link with JSX variables

When inserting normal HTML elements with React variables in JSX, there are a few ways to go about it. One option is to use the dangerouslySetInnerHTML attribute or you can utilize a package like html-react-parser from npm. The following code demonstrates ...

What is the process for assigning a function and its arguments as a callback in programming?

Here is a code snippet for your consideration: $scope.delete=function(){ foo('x',3); }; How can we improve the clarity of this code snippet when the callback function contains only one line that calls another function? It's important ...

Controlling the display and status of DIV elements as radio button choices within a React application

I am seeking the React.js solution to a common challenge. I have five DIVs that will function as radio button options when clicked. This is what the HTML might look like: //List of option DIVs which act as radio buttons when clicked const options = () = ...

Exploring Angular unit testing using Jasmine: Techniques to customize or delete spyOn

Current software versions for AngularJS and Jasmine: AngularJS v1.2.26 Jasmine v2.2.0 I am facing an issue with a spyOn. When attempting to change or remove its behavior, I encounter the following error message: Error: getUpdate has already been spied u ...

The Node.js callback is executed before the entire function has finished executing

const fileSystem = require('fs'); const filePath = require('path'); module.exports.getFiles = function(filepath, callback) { let files = []; fileSystem.exists(filepath, function(exists){ if(exists){ fileSy ...

What is the best way to retrieve JSON data from the server?

Currently, I have some code that sends data to a server: HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(URL); try { HttpResponse response = httpclient.execute(httppost); } catch (ClientProtocolExc ...

How can the value attribute be obtained from the click class?

$(document).on('click','.edit', function(){ var appid = $(this).getAttribute('value'); I am trying to figure out how to save the value of the "value" attribute for an image with the edit class. Can anyone help me with thi ...

sending data to a PHP file via an AJAX request

I am attempting to send a JSON string and a variable through an AJAX call in order to edit the query in a PHP file. My code is structured as follows: queryData = { "data": { "data_string": { "data": "oil", "default_fiel ...

Retrieve data from a JSON file

I have a JSON file containing various player data, and I need to extract the "Name" field from it. { "player": [ { "Position": "TEST", "Name": "TEST", "Squad_No": "TEST", "Club": "TEST", "Age": "TEST" }, ...

Alter the ng-repeat values that are dynamically added from a common source

I am facing an issue where dynamically added ng-repeat values are being changed across all divs instead of the selected one. In my code below, clicking on dynamically appended divs shows a form on the right side allowing input text fields. However, I want ...

Tips for Selecting the DIV Element using jQuery

I am faced with the challenge of integrating this particular set of div tags: <div id="target-share"> <a href="#" title="" id="to-chosen" class="default"><span class="to-admin">Admin</span></a> <ul id="select-shareto"> ...

What is the best way to transfer the value of one directive attribute to another directive in AngularJS?

For instance: <custom-main> <custom-sub1 att-name="test"></custom-sub1> <custom-sub2></custom-sub2> </custom-main> JavaScript Source Code bosAppModule.directive('custom-main',[&apos ...

What is the best way to integrate a Sequalize API into my React project?

I am looking for guidance on how to retrieve records from my MYSQL database and integrate it into my API. I am unsure about the routing process (do I need to create a component?) and struggling to find resources on using sequelize with React. Any assista ...

The initialized Javascript array solely consists of undefined elements, without any of the expected values

I was under the impression that I knew how to declare JavaScript arrays, but in this particular script, I seem to be stuck in an infinite loop of undefined elements within the array. In my code, I define three arrays containing numbers—two with multiple ...

Have you attempted to configure a JSON file to facilitate language translations?

I need some guidance on structuring my data.json file efficiently. Currently, it is set up as shown in the example below. The goal is to have a drop-down menu where users can select a language and then display 50 different pages with specific content. I wa ...

Why isn't my object updating its position when I input a new value?

<hmtl> <head> <!--<script src='main.js'></script>--> </head> <body> <canvas id='myCanvas'> </canvas> <script> function shape(x,y){ this.x=x; this.y=y; var canvas = document.get ...

Easier method for creating json body for reqwest post requests

I've implemented a post call that adds one line in register, and while it is functional, the code is cumbersome to write and read. Here's how it currently appears: static CLIENT: Lazy<Client> = Lazy::new(|| Client::new()); static GENER ...

Searching for the clicked tr element within a tbody using jQuery

Here is my customized HTML table layout <table> <thead> <tr> <td class="td20"><h3>Client Name</h3></td> <td class="td20"><h3>Details</h3></td> ...