1

I am wanting to change the value inside a json object using a function that allows you to pass in what key you want to change (pName)

var users = {
  john: {
    read: true,
    write: false
  },
  mike: {
    read: true,
    write: false
  }
}

var chgPermission = function (userName, pName, pValue) {
  if (users[userName]) {
    users[userName].pName = pValue;
  } else {
    console.log(`Could not find: ${userName}`)
  }
}

chgPermission("mike", "write", true)

This does not work because it looks for users[username].pName (which does not exist) instead of users[userName].write

what do i need to do to have the function allow me to change the value of the key that is passed in.

thank you

Asuu
  • 173
  • 1
  • 11

2 Answers2

2

I think you want something like this:

var chgPermission = function (userName, pName, pValue) {
  if (users[userName]) {
    users[userName][pName]= pValue;
  } else {
    console.log(`Could not find: ${userName}`)
  }
}
Pablo DbSys
  • 532
  • 1
  • 7
  • 17
1

Just change users[userName].pName to users[userName][pName].

Ahmed Agiza
  • 360
  • 1
  • 7