在jquery中为对象数组中的对象赋值

时间:2020-11-28 20:11:14

I have an array of objects

我有一个对象数组

object will be in below format

对象将采用以下格式

var newUserDetail={"Age":"21","name":"Vicky","UserId":"198303"};

Now I am trying to compare UserId and replace the values

现在我试图比较UserId并替换值

//usersList contains array of newUserDetail kind of objects

jQuery(usersList).each(function(){
if(this.UserId==newUserDetail.UserId){
this=newUserDetail;
}
});

But it throws an error

但它会引发错误

Invalid left-hand side in assignment

2 个解决方案

#1


1  

Set the array entry:

设置数组条目:

jQuery(usersList).each(function (i) {
    if (this.UserId == newUserDetail.UserId) {
        usersList[i] = newUserDetail;
        return false; //if you want to break the loop
    }
});

#2


1  

Try this

$(document).ready(function() {
  var newUserDetail = {
    "Age": "21",
    "name": "Vicky",
    "UserId": "198303"
  };

  var tm = {
    "Age": "21",
    "name": "Vicky",
    "UserId": "198303"
  };
  $.each(newUserDetail, function(k, i) {
    if (i == tm.UserId) {
      alert("User ID match");
    }


  })



})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#1


1  

Set the array entry:

设置数组条目:

jQuery(usersList).each(function (i) {
    if (this.UserId == newUserDetail.UserId) {
        usersList[i] = newUserDetail;
        return false; //if you want to break the loop
    }
});

#2


1  

Try this

$(document).ready(function() {
  var newUserDetail = {
    "Age": "21",
    "name": "Vicky",
    "UserId": "198303"
  };

  var tm = {
    "Age": "21",
    "name": "Vicky",
    "UserId": "198303"
  };
  $.each(newUserDetail, function(k, i) {
    if (i == tm.UserId) {
      alert("User ID match");
    }


  })



})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>