如果存在键名数组,则更改对象的深层嵌套键值 [英] Change deeply nested key value of an object if there's an array of key names
本文介绍了如果存在键名数组,则更改对象的深层嵌套键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象和相同对象键的数组:
I have an object and an array of the same object keys:
var obj = {
'fieldOne': {
'fieldTwo': {
'fieldThree': {
'fieldFour': {
'someNestedKey': 'test'
}
}
}
}
}
var keysArr = ['fieldOne', 'fieldTwo', 'fieldThree', 'fieldFour', 'someNestedKey'];
是否可以使用keys数组更改 someNestedKey值?
Is there a way to change the 'someNestedKey' value using the keys array ?
仅通过索引访问 someNestedKey是行不通的,因为键数组中可能包含或多或少的键。
我尝试以某种方式使用数组长度,但似乎无法正常工作。
我对编程还比较陌生,将不胜感激。
Simply accessing the 'someNestedKey' by indexes won't work, because keys array may have more or less keys in it. I tried somehow using array length, but I can't seem to get it working. I'm relatively new to programming, would much appreciate any help.
推荐答案
您可以走这条路,检查以下元素是否存在。如果未将对象分配给新属性。
You could take the path and make a check if the following element exist. If not assign an object to the new property.
然后返回该属性的值。
在
function setValue(object, path, value) {
var way = path.slice(),
last = way.pop();
way.reduce(function (r, a) {
return r[a] = r[a] || {};
}, object)[last] = value;
}
var obj = { fieldOne: { fieldTwo: { fieldThree: { fieldFour: { someNestedKey: 'test' } } } } },
keysArr = ['fieldOne', 'fieldTwo', 'fieldThree', 'fieldFour', 'someNestedKey'];
setValue(obj, keysArr, 42);
console.log(obj);
这篇关于如果存在键名数组,则更改对象的深层嵌套键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文