gpt4 book ai didi

Javascript(子)对象通过键数组访问

转载 作者:行者123 更新时间:2023-11-29 10:36:46 27 4
gpt4 key购买 nike

是否可以通过键数组在对象中设置变量?例如我有这个对象:

var obj = {'outer': {'inner': 'value'} };

并希望设置由键数组选择的值:

var keys = ['outer', 'inner'];

到一个新的值 'newValue' 以获得这个结果:

obj = {'outer': {'inner': 'newValue'} };

最佳答案

您可以做的是遍历键数组,确保每个键都存在并指向另一个对象,直到到达最后一个键,您可以使用它来设置新值。

function setVal(obj, keys, value) {
var o = obj,
len = keys.length;

// iterate through all keys, making sure each key exists and points to an object
for (var i = 0; i < len - 1; i++) {
var key = keys[i];

// check if the current key exists and is an object
if (obj.hasOwnProperty(key) && typeof obj[key] === 'object' && obj[key]) {
o = o[key];
} else {
// return false or throw an error cause the key is not an object or is missing.
}
}

// update the value at the last key
o[keys[len - 1]] = value;
}

这是一个运行示例:

function setVal(obj, keys, value) {
var o = obj,
len = keys.length;
for (var i = 0; i < len - 1; i++) {
var key = keys[i];
if (obj.hasOwnProperty(key) && typeof obj[key] === 'object' && obj[key]) {
o = o[key];
} else {
throw new Error('Key ' + key + ' is not an object or is missing.');
}
}
o[keys[len - 1]] = value;
}

var obj = {
'outer': {
'inner': 'value'
}
};

var validKeys = ['outer', 'inner'];
var invalidKeys = ['outer', 'inner', 'extra'];

console.log('Setting valid keys');
setVal(obj, validKeys, 'new value');
console.log(obj);

console.log('Setting invalid keys');
setVal(obj, invalidKeys, 'new value');
console.log(obj);

如果您想让您的方法只更新现有键值而不设置新键值,您可以使用 hasOwnProperty 将最后一个语句包装在 setVal 中:

// if object already has the last key, update its value
if (o.hasOwnProperty(keys[len - 1])) {
o[keys[len - 1]] = value;
} else {
// throw an error or return false since the last key doesn't exist.
}

关于Javascript(子)对象通过键数组访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35282950/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com