0

So I have an array of objects like this:

var data = [{
id : 1,
firstName : 'John',
secondName : 'Doe',
email : 'johndoe@mail.com'}];

I have a function called update which asks user for an id and updates the data with same id with the values given by the user. For example:

function update(firstName,lastName,email,id)

How can I update the data array based on id provided by the user and also return true if the specified id was found?

Josh
  • 93
  • 1
  • 6

4 Answers4

0

You can use Destructuring Assignment to pass an Object as a Function's Parameters:

var data = [{
id : 1,
firstName : 'John',
secondName : 'Doe',
email : 'johndoe@mail.com'}];


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

data.forEach(x => update(x))
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0
function update(firstName, lastName, email, id) {
  var l = 0;
  while (l<data.length) { // cycle through array and search for id
    if (data[l].id == id) { // update values of array when found
      data[l].firstName = firstName;
      data[l].lastName = lastName;
      data[l].email = email;
      return true; // return that value found and updated
    }
    l++;
  }
  return false; // return that no value was found
}
0

Heres one way of doing it -

function update(firstname,lastname,email,id) {
    let found = false;
  for (let i = 0; i < data.length; i++) {
     if (data[i].id === id) { 
      if (firstname) data[i].firstname = firstname;
       if (lastname) data[i].lastname = lastname;
        if (email) data[i].email = email;
       found = true;
       break;
     }
   }
return found;
}
Deon Rich
  • 589
  • 1
  • 4
  • 14
0
var data = [{
                   id : 1,
                   firstName : 'John',
                   secondName : 'Doe',
                   email : 'johndoe@mail.com'}];

function update(id, firstName, lastName, email){
    let object = data.find(element => element.id === id)

    if(!object){
        return false
    }

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

console.log(update(1, 'Mike', 'Smith', 'mike@mail.com'))

console.log(data[0])

You need to ensure that the Array only will have an Object with the same Id, if not, only one will be updated

ManuelMB
  • 1,254
  • 2
  • 8
  • 16