Transfer data from distinct arrays to separate variables

I have 2 arrays structured like this:

let dataA = [{"id": "a1", "name": "Alpha"}, {"id": "a2", "name": "Beta"}, {"id": "a3", "name": "Gamma"}, {"id": "a4", "name": "Delta"}, {"id": "a5", "name": "Omega"}]

and

let dataB = [{"a1": 0, "a2": 100000, "a3": 500000, "a4": 300000, "a5": 45900}]

How can I transfer values from dataB to dataA?

For example, how do I push the value of dataB.a4, which is 300000, to dataA.id == a4?

I would like the final result to be similar to:

let result = `[{"id": "a1", "name": "Alpha", "values": 0}, {"id": "a2", "name": "Beta", , "values": 100000}, {"id": "a3", "name": "Gamma", "values": 500000}, {"id": "a4", "name": "Delta", "values": 300000}, {"id": "a5", "name": "Omega",  "values": 45900}]`

Any assistance would be greatly appreciated as I have been struggling with this for days.

Thank you in advance.

Answer №1

To dynamically add a values key with the value of payrollbalance[0] based on the JSON key, you can utilize the Array.map() method.

let payrollname = [{"code": "a1", "name": "Loan A"}, {"code": "a2", "name": "Loan B"}, {"code": "a3", "name": "Loan C"}, {"code": "a4", "name": "Loan D"}, {"code": "a5", "name": "Loan E"}]

let payrollbalance = [{"a1": 0, "a2": 100000, "a3": 500000, "a4": 300000, "a5": 45900}]

let result = payrollname.map(item => ({
  ...item,
  values: payrollbalance[0][item.code]
}));

console.log(result);

Answer №2

Create a program to search an array, locate the index, and then update it

let payrollname = [{"code": "a1", "name": "Loan A"}, {"code": "a2", "name": "Loan B"}, {"code": "a3", "name": "Loan C"}, {"code": "a4", "name": "Loan D"}, {"code": "a5", "name": "Loan E"}]
let payrollbalance = [{"a1": 0, "a2": 100000, "a3": 500000, "a4": 300000, "a5": 45900}]
var result = [];
let pblance = payrollbalance[0]
for(let p in pblance)
{
  let index = payrollname.findIndex(el => el.code==p)
  let pname = payrollname[index]
  pname.values = pblance[p];
  result.push(pname)
}
console.log(result);

Answer №3

yes, this snippet is sure to deliver!

let employees = [{"id": "001", "name": "John Doe"}, {"id": "002", "name": "Jane Smith"}, {"id": "003", "name": "Michael Johnson"}, {"id": "004", "name": "Emily Brown"}, {"id": "005", "name": "David Lee"}]
let salaries = [{"001": 60000, "002": 75000, "003": 90000, "004": 55000, "005": 80000}]
let payrollResults = []
let index = 0
employees.forEach(person => {
    let payAmount = salaries[0][person.id]
    person.salary = payAmount;
    payrollResults[index] = person
    index=index+1
});
console.log(payrollResults)

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

Having difficulty grasping the concept behind the prepend method's functionality

I encountered an issue with my code, where I successfully created a <th> element initially, but faced problems when trying to create it repeatedly. function createTH(){ var noOfRow = document.getElementById("addItemTable").rows.length; var t ...

The feature to hide columns in Vue-tables-2 seems to be malfunctioning

The issue I'm facing is with the hiddenColumns option not working as expected. Even when I set it to hiddenColumns:['name'], the name column remains visible. I've updated to the latest version, but the problem persists. UPDATE I am tr ...

A guide on extracting an integer value from JSON data using Qt

Is there a way to retrieve the integer value from a QJsonValue object? Let's say we have the following JSON data: { "res": 1, "message": "Common error" } We want to extract the value of "res" from this data, so we attempted t ...

Tips on how to prevent certain classes from being impacted by a hue-rotate filter applied to all elements on a webpage

I am currently in the process of adding a feature that allows users to choose between a dark or light theme, as well as select a specific theme color for the app. The implementation involves using CSS filters such as invert(1) for the dark theme and hue-ro ...

Tips for creating Firestore rules for a one-on-one messaging application

After creating a one to one chat app for a website using Firebase and Firestore, I am now looking to set up the Firebase Firestore rules for the same. The functionality of the app involves checking if the user is [email protected], then retrieving chatids ...

What is the best way to collapse a button in asp.net using javascript after setting it to hidden?

I have a scenario where I have 3 buttons in a row on my asp.net page. Using JavaScript, I am setting the middle button (ButtonSR) to invisible. However, I want the button below it to move up and take its place instead of leaving an empty space. ...

The error message "The useRef React Hook cannot be invoked within a callback function" is displayed

I'm currently working on developing a scroll-to feature in Reactjs. My goal is to dynamically generate referenced IDs for various sections based on the elements within an array called 'labels'. import { useRef } from 'react'; cons ...

Creating a personalized context menu in Javascript: The ultimate guide to incorporating copy and paste features

We are developing a unique context menu for our online text editor, complete with copy/paste options. However, we encountered difficulties accessing the system clipboard from within the browser. It once seemed impossible to achieve this, as discussed in th ...

Loop through items in a list using Angular.js and display each item within an <

I am facing an issue where the model returned from the server contains html tags instead of plain text, such as b tag or i tag. When I use ng-repeat to create a list based on this model, the html is displayed as pure text. Is there a filter or directive av ...

Store user input in a paragraph

I want to create a unique program that allows users to input text in a field, and when they click "Start", the text will appear in a paragraph backwards. I plan to use Html, jQuery, and CSS for this project. Can anyone provide guidance on how to achieve th ...

The select2 ajax functionality encountered an error: Uncaught TypeError - Unable to access the 'context' property as it is undefined

Trying to make an AJAX request using the Select2 jQuery plugin. The query appears to be functioning properly, but the problem arises when ".context===undefined" is called on the "data" object: Uncaught TypeError: Cannot read property 'context' o ...

Ways to minimize renders while toggling a checkbox

I'm currently working on developing a high-performance checkbox tree component. To manage the checked checkboxes, I am utilizing a parent level state that contains an array of selected checkbox IDs => const [selected, setSelected] = useState([]); ...

¿What is preventing me from merging two arrays within this query handler?

I'm facing an issue while trying to merge arrays from a request with existing arrays in a MongoDB database. Despite my attempts, the arrays do not seem to be merging as expected. Can anyone help me identify what might be causing this problem? router.p ...

Manipulate SVG elements by dragging them along the boundary of the path

Looking to achieve a specific functionality where I can drag and drop an element along the edges of a drawn path, rather than inside the path itself. To clarify, the goal is to move the red marked element on the black line bordering the path, allowing move ...

My code is ready, but unfortunately, it is not retrieving the data as expected from my JSON file

I'm encountering an issue with my code where it's not fetching data from my JSON file. I keep getting 0 arguments and I'm unsure of what I'm doing wrong. Can someone provide assistance? This project is built using Angular. I have my ...

Transmit data in the form of a buffer

const response = await client.render(data); const Writable = require('stream').Writable; var buffer = []; const myWritableStream = new Writable({ write(chunk, encoding, callback) { ...

Looking for a way to make the spinner disappear in puppeteer while waiting?

What is the most effective way to wait for the spinner to vanish before clicking on a button? Check out this example ...

When attempting to import Three.js canvas on Github Pages, a 404 error is received

While attempting to host my webpage with a three.js background, I encountered an issue where everything loads properly when hosted locally, but nothing loads when pushed to GitHub pages - only the HTML is visible. I am utilizing Vite to package my code an ...

Application route is failing to direct to the HTML page

On my MEAN stack website, I am trying to make the browser navigate to a file named 'findCable.html' but it keeps directing to 'singleCable.html'. I have double-checked the angular routing file and backend routes, but can't see ...

How can the value of a button be displayed in an input box using an onclick function?

When the button '1' is clicked, it displays the value "1" inside a <!p> tag. However, the second button '2' does not display the value "2" in the input box. Even though both functions are identical. //Function with working func ...