我想使用一个函数来更改 json 对象内的值,该函数允许您传入要更改的键 (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)
这不起作用,因为它查找 users[username].pName (不存在)而不是 users[userName].write
我需要做什么才能让该函数允许我更改传入的 key 的值。
谢谢
最佳答案
我想你想要这样的东西:
var chgPermission = function (userName, pName, pValue) {
if (users[userName]) {
users[userName][pName]= pValue;
} else {
console.log(`Could not find: ${userName}`)
}
}
关于javascript - json对象根据传入的键更改值函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52526460/