What is the best way to sequentially update an array of objects using another array as an argument in JavaScript using the .map() method?

As a novice student, I am currently working on improving my understanding of .map(). My goal is to create a callback function that can generate a list of full names by assigning last names from the lastNames array to the corresponding employees in the employees object.

const lastNames = ["Smith", "Anderson"];

const employees = [
  {
    name: "Jim",
    familyName:"",
  },
  {
    name: "Jill",
    familyName: "",
    
  }
];

I attempted to accomplish this task by creating a function called lastNameUpdater, which should return a new array of objects with updated full names. However, I seem to have taken a wrong turn, possibly due to mismatched index numbers:

function lastNameUpdater(arr, objArr) {
  let matchNumber = arr.findIndex() === objArr.findIndex();
  const fullNames = objArr.map((element) => {
    return matchNumber;
    if (matchNumber) {
      return objArr.key = arr;
    }
    return fullNames;
  })
}

lastNameUpdater(lastNames, employees);

Answer ā„–1

To easily update the employee family names, leverage the second parameter `index` in the callback function and utilize spread notation to replace the existing `familyName` attribute with the corresponding value from the `lastNames` array:

function update(employees, lastNames) {
  return employees.map(function(employee, index) {
    return {...employee, familyName: lastNames[index]}
  });
}

const lastNames = ["Smith", "Anderson"];
const employees = [
  {
    name: "Jim",
    familyName:"",
  },
  {
    name: "Jill",
    familyName: "",
    
  }
];

console.log(update(employees, lastNames))

Answer ā„–2

You have the option to utilize the index parameter provided in the map function to retrieve the corresponding last name from another array.

const lastNames = ["Smith", "Anderson"];
const employees = [
  {
    name: "Jim",
    familyName:"",
  },
  {
    name: "Jill",
    familyName: "",
  }
];
const result = employees.map((obj, index) => ({...obj, familyName: lastNames[index]}));
console.log(result);

Answer ā„–3

Your approach to using findIndex is incorrect; in fact, you may not even need it at all. For more information, you can refer to this source

What would be more beneficial for your task is utilizing the second parameter of the map method, which represents the index of the current element in the array. You can then use this index to retrieve the corresponding element from the lastNames array.

const lastNames = ['Smith', 'Anderson'];

const employees = [
  {
    name: 'Jim',
    familyName: '',
  },
  {
    name: 'Jill',
    familyName: '',
  },
];

function lastNameUpdater(arr, objArr) {
  const fullNames = objArr.map((element, index) => ({
    ...element,
    familyName: arr[index],
  }));
  return fullNames;
}

// Output:
// [
//     { name: 'Jim', familyName: 'Smith' },
//     { name: 'Jill', familyName: 'Anderson' }
// ]
console.log(lastNameUpdater(lastNames, employees));

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

Previewing an uploaded image before submitting with FileBase64: A step-by-step guide

How can I implement a preview for an uploaded image before submitting the form? I have the upload functionality working but I would like to add a preview feature for the image. Below is the code snippet I am currently using: const [shop, setShop] = us ...

Issue with joining tables in query on Cordova Mobile app

I have 2 queries that will return results which I plan to use in JSON format. The first query is $query = "SELECT * FROM info_location WHERE location_id=".$id.""; and the second query $query = "SELECT t1.location_id,t1.street,t1 ...

What is the best way to implement a dynamic sidebar component using React and Material UI?

I have been attempting to implement a responsive sidebar using React Material Design, but I am struggling to achieve the desired outcome. The main goal is for the page content to remain responsive when the sidebar is opened, without overlapping on the pag ...

Encountering an issue with CORS while running a node application on a local server

I am facing a challenge where I want to send POST data from a JavaScript script to a node server application using express. However, when I attempt to send the data, I encounter an error stating: CORS-Header 'Access-Control-Allow-Origin' does not ...

What is the process for retrieving the text from a remotely loaded "<script>" element?

Iā€™m currently in the process of developing an AJAX-enabled Manga reader application for Onemanga using Greasemonkey, specifically JS/jQuery. My issue lies in needing to run one of the inline scripts on their page to update the next page URL. My attempte ...

How to access vue.js 3 single file component functions from within a script tag

Imagine having a single file component structured like this: <template> // content irrelevant </template> <script> export default { data() { return { redLocations: [ "Isfahaan", "Qom", ...

Generating a new division element with a unique identifier and subsequently making adjustments to it

Just starting out with HTML and JS here, so please excuse my lack of experience and not-so-great English. I have an ID on an HTML element that I want to add content to using a function. Additionally, I need to create another element (inside the first one) ...

Difficulty encountered in altering button color when the password and confirm password fields are the same in a Vue.js project?

password: '', confirmPassword: '', computed: { empty() { return this.user.password === '' || this.user.confirmPassword === ''; }, equal() { return this.user.password === this.user.confirmPass ...

Next.js Project Encounters Compilation Error Due to Tailwind CSS Custom Class

I am currently working on a Next.js project and incorporating Tailwind CSS. Unfortunately, I have come across a compilation error that I am struggling to resolve. The error specifically pertains to a custom utility class that I defined in my theme.css file ...

Is there a way to incorporate a component into Particle.js?

I attempted to encase the Particle around the component but it's not functioning correctly import React from "react"; import { render } from "react-dom"; import Particles from "./Particles"; import "./index.css" ...

The output of jQuery('body').text() varies depending on the browser being used

Here is the setup of my HTML code: <html> <head> <title>Test</title> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function initialize() { var ...

Trouble with downloading files using the anchor (a) tag in React

Every time I try to click on the a tag to download the file named approved_leads.zip, I keep receiving an error message saying "failed - no file". It seems like the path is correct, so I'm not sure what is causing the issue. <a href="../../ass ...

Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model: var userSchema = new mongoose.Schema( { userName: {type: String, required: true}, firstName: {type: String}, lastName: {type: String}, password: {type: String, required: true}, ...

Tips for adjusting the position of an icon when encountering a line break using Javascript or CSS

After some trial and error, I managed to get it working, but only when the page is initially loaded and not in a responsive manner. Below is the JavaScript code I used. if ( $(".alert-box").height() >= 90 ) { $('.img').css(&apos ...

What is the best way to determine if any of the list items (li's) have been marked as selected?

<div id='identifier'> <ul id='list'> <li id='1' class="">a</li> <li id='2' class="">a</li> <li id='3' class="">a</li> <li id='4' class=" ...

What is the best way to retrieve both the start and end date values from a React date range picker component

I have integrated a date range picker npm package called react-date-range into my code. On my screen, there is an "Apply Dates" button. When this button is clicked, I want to retrieve the selected date range value. How can I achieve this onclick event? ...

An issue with JSPDF arises when used on mobile devices

Currently, I am working on a project to create a responsive web application, which involves utilizing JSPDF for generating PDF reports directly from HTML. For a demonstration of the functionality, you can check out this Demo. Unfortunately, when trying t ...

Search through an array of Ajax responses in Vue.js as the user types

I have encountered an issue where I am attempting to filter a list based on user input in a text box that is populated via an Ajax call. It seems like the filtering process is being applied before the Ajax call has completed. Here is the structure of the ...

Why are imported modules unable to reach global variables in Node?

As I delve deeper into using ES6 and organizing my code across multiple files for better readability and version control, I've encountered an issue that has me puzzled. In one of my scenarios, I have a class defined in a separate file called class.js, ...

Customize the CSS for a Material UI popover styling

I am currently working with a Material UI popover and attempting to apply CSS styles to it. This is the code for my popover component: import React, { memo, useCallback } from 'react'; import PropTypes from 'prop-types'; import { ...