Adjusting the attributes of an item identified by a unique identifier

I am working with an array of objects that looks like the following:

var data = [{
id: 1,
firstName: 'John',
secondName: 'Doe',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ff5f0f7f1fbf0fadff2fef6f3b1fcf0f2">[email protected]</a>'}];

In my code, I have a function called update which prompts the user for an id and updates the data object with the same id using the values provided by the user. For example:

function update(firstName, lastName, email, id)

I am looking for a way to update the data array based on the id provided by the user and also return true if the specified id was found in the array.

Answer №1

Utilizing Destructuring Assignment to transfer an Object as arguments for a Function:

var users = [{
id : 1,
firstName : 'Jane',
lastName : 'Doe',
email : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd97929593999298bd909c94a1919292">[email protected]</a>'}];


function updateUser({firstName, lastName, email, id}){
  if(id == '1'){
    console.log(`update ${firstName}`)
  }
}

users.forEach(user => updateUser(user))

Answer №2

function modifyUserInfo(firstName, lastName, email, id) {
  var index = 0;
  while (index<dataCollection.length) { // looping through data array to find specified ID
    if (dataCollection[index].id == id) { // update values in the array when ID is found
      dataCollection[index].firstName = firstName;
      dataCollection[index].lastName = lastName;
      dataCollection[index].email = email;
      return true; // indicating that value was found and updated successfully
    }
    index++;
  }
  return false; // indicating that no matching value was found for the given ID
}

Answer №3

Here's a possible solution:

function modifyUser(firstName, lastName, email, userId) {
    let userFound = false;
    for (let i = 0; i < userData.length; i++) {
        if (userData[i].id === userId) { 
            if (firstName) userData[i].firstName = firstName;
            if (lastName) userData[i].lastName = lastName;
            if (email) userData[i].email = email;
            userFound = true;
            break;
        }
    }
    return userFound;
}

Answer №4

let information = [{
                   id : 1,
                   firstName : 'John',
                   secondName : 'Doe',
                   email : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec4c1c6c0cac1cbeec3cfc7c280cdc1c3">[email protected]</a>'}];

function updateData(id, firstName, lastName, email){
    let user = information.find(item => item.id === id)

    if(!user){
        return false
    }

    user.firstName = firstName
    user.lastName = lastName
    user.email = email
 
    return true
}

console.log(updateData(1, 'Mike', 'Smith', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6367656b4e636f6762206d6163">[email protected]</a>'))

console.log(information[0])

To ensure that the array only contains an object with the same Id, only one will be updated

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

Is there a way to determine the percentage between two specified dates?

If I have a specified start and end date, I am interested in knowing the progress percentage achieved from the start date up to the current date compared to the end date. To put it simply: I would like to determine how far along I am towards the end date i ...

Create a collection showcasing only the values present in an array based on a specified percentage

An array named "data" consists of the given information. [['amazon', 'phone', 'serious', 'mind', 'blown', 'serious', 'enjoy', 'use', 'applic', &apos ...

Skrollr triggers a fade-in effect once the user reaches a specific distance from the bottom of the

Using skrollr, I have a div positioned at the bottom of some content that I want to fade in once the screen reaches its level. I attempted various examples found on their cheat sheet but had no success. This div is situated above the footer (500px from t ...

Navigating the DOM in Vue.js: A Step-by-Step Guide

While I am trying to utilize Vue.js to access the DOM, the code I have written within the mounted() lifecycle is not producing any results. Interestingly enough, the same code functions perfectly fine when using vanilla JavaScript. I have incorporated the ...

Dynamically alter routing in Express by retrieving route paths from a JSON document

My goal is to dynamically update my route in Express using a JSON file that stores the specific link. The JSON data resides in articles.js and appears as follows: title: 'title1', link: 'title2', creator: 'user1', crea ...

Troubleshooting Sequelize's hasMany and belongsTo relationships

Looking to create 2 tables in Mysql using the power of node.js & sequelize.js. The two models we're working with are User and Company Here's what the fields for User look like: - id - username - password And for Company, here are its fields: - ...

What is causing the issue with transmitting the server datetime to my local jQuery script?

I am facing an issue with my timeoftheserver.php page setup. The PHP code is quite simple: <?php echo date('D, d M y H:i:s'); ?> Similarly, the script on my local machine is also straightforward: var today; try { today = new Date($. ...

Tips for stopping special characters from being copied and pasted into a number field

My goal is to ensure that only numbers can be copied and pasted into the 'number field'. By preventing the copy and paste of characters like 'e', '+', '-', and '.', I can ensure that the number field only c ...

Tips for intentionally refreshing or crashing a browser tab by utilizing the response from an AJAX request

Yesterday, we deployed new code to our production environment which included a polling mechanism using setInterval() in Javascript. This feature makes an AJAX request every 15 seconds to update clients with the server. Surprisingly, even though only around ...

Executing a function that includes showModalDialog outside of an iframe might display the incorrect page

This website structure looks like: `--main.html `--dialog.html `--folder `--iframe.html The code for each page is as follows: main.html: <html> <head> <script type="text/javascript"> function t ...

How can you ensure that the results are displayed only when all the fields in the form are properly

Take a look at the code below: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ ...

How to transfer a C library callback to a NodeJS EventEmitter with the help of node-addon-api

In the process of developing a node module that integrates Alex Diner's cross-platform gamepad code using the Node-Addon-API, I encountered an interesting challenge. Making the module function as an EventEmitter and exposing callback functions throug ...

The JQuery duplication process did not function as anticipated

This question builds on a previous one related to jQuery cloning and incrementing IDs. The issue is that when adding new elements, the IDs are not being generated in the correct sequence. For example, if the initial ID is expy-1, clicking "add more" should ...

An effective method for cutting off text while preserving HTML styling using jQuery

Is there a way to truncate text using jQuery while preserving the HTML formatting? I attempted the code below, but it doesn't maintain the HTML tags. var truncate = function() { $('p.truncated').text(function(index, oldText) { if (old ...

Screen white on the right side

I am encountering an issue where my screen shows white on the side when I scroll to the right. I am unsure how to remove it and cannot locate the problem in the code. Here is a link to the code: https://jsfiddle.net/y3j01hbt/ In the provided code, there i ...

Sending a file stream with specific file name and extension in NodeJS: A comprehensive guide

Currently, I am utilizing nodejs to transmit file streams to express response var fileReadStream = fs.createReadStream(filePath); fileReadStream.pipe(res); However, the issue arises on the front-end where the file is solely downloadable with the "download ...

Creating a smooth JQUERY fade slideshow with seamless transitions, no white gaps in

I am having trouble with the slideshow on my Wordpress website www.2eenheid.de. I want the images to fade smoothly between each other instead of fading into a white background color first and then into the next image. Can anyone help me find a solution for ...

`Misconceptions in understanding AngularJS directives`

I am currently working on a new app that includes both a header and main view, utilizing directives. At first, I had the directive in its own file but decided to relocate it into app.js in order to resolve an issue. Throughout this process, I have experim ...

How can I trigger an event to append a UL element using

Can anyone suggest a more elegant solution for handling an append/remove event from an element without having to manually trigger an event or resorting to other methods? It would be great if there was a way to do something like this: $('#id').o ...

Utilizing Parameters in Route Mapping within Node.js API

Currently, I am in the process of setting up an API for my website. However, I am encountering some difficulties with the route params. At the moment, I have implemented two routes: const route1 = require('./routes/route1') const route2 = requir ...