我们可以通过JSON键查找并设置值吗?

时间:2018-09-14 05:41:34

标签: javascript jquery

我有以下对象

var test = {
  "Employees": [
    {
      "userId": "rirani",
      "jobTitleName": "Developer",
      "firstName": "Romin",
      "lastName": "Irani",
      "preferredFullName": "Romin Irani",
      "employeeCode": "E1",
      "region": "CA",
      "phoneNumber": "408-1234567",
      "emailAddress": "romin.k.irani@gmail.com",
      "active" : true
    },
    {
      "userId": "nirani",
      "jobTitleName": "Developer",
      "firstName": "Neil",
      "lastName": "Irani",
      "preferredFullName": "Neil Irani",
      "employeeCode": "E2",
      "region": "CA",
      "phoneNumber": "408-1111111",
      "emailAddress": "neilrirani@gmail.com",
      "active" : true
    },
    {
      "userId": "thanks",
      "jobTitleName": "Program Directory",
      "firstName": "Tom",
      "lastName": "Hanks",
      "preferredFullName": "Tom Hanks",
      "employeeCode": "E3",
      "region": "CA",
      "phoneNumber": "408-2222222",
      "emailAddress": "tomhanks@gmail.com",
      "active" : true
    }
  ]
}

对象是动态的(Employees可能存在或不存在)

如果用户ID为nirani,我们可以将active的值设置为false吗?

尝试如下

test.find('userId').disabled = 'false';

1 个答案:

答案 0 :(得分:0)

您可以使用本地javascript:

if (test.Employees) {
  for(var i = 0; i < test.Employees.length; i++) {
    var employee = test.Employees[i];
    if (employee.userId === 'nirani') {
      employee.active = false;
    }
  }
}