【问题标题】:Updating the properties of an object with a specific id [duplicate]更新具有特定 ID 的对象的属性 [重复]
【发布时间】:2021-06-11 14:39:13
【问题描述】:

所以我有一个这样的对象数组:

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

我有一个名为 update 的函数,它向用户询问 id 并使用用户给出的值更新具有相同 id 的数据。例如:

function update(firstName,lastName,email,id)

如何根据用户提供的id更新数据数组,如果找到指定的id也返回true?

【问题讨论】:

    标签: javascript arrays function object


    【解决方案1】:
    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])
    

    您需要确保Array只有一个具有相同Id的Object,如果没有,则只会更新一个

    【讨论】:

      【解决方案2】:

      这是一种方法-

      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;
      }
      

      【讨论】:

        【解决方案3】:
        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
        }
        

        【讨论】:

          【解决方案4】:

          您可以使用解构赋值将对象作为函数的参数传递:

          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))

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-01-28
            • 2017-10-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多