通过属性名称数组访问嵌套对象 [英] Access nested objects via array of property names
本文介绍了通过属性名称数组访问嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的对象(简化):
Say I have an object like this (simplified):
var options = {
boxes: {
size: {
x: 15,
y: 18
},
shadow: {
[...]
}
};
我有一个名字数组:
var names = ['boxes', 'size', 'x'];
根据数组在对象内部获取/设置值的简单方法是什么,在本例中是:
What is an easy way to get/set a value inside the object according to the array, in this example it would be:
options.boxes.size.x = somevalue;
有什么想法吗?
推荐答案
没有简单的内置方法可以做到这一点.您必须编写自己的方法:
There's no easy, built-in method for doing this. You'd have to write your own method:
function getPath(obj, props) {
for(var i = 0; i < props.length; i++) {
if (props[i] in obj) {
obj = obj[props[i]];
} else {
return; // not found
}
}
return obj;
}
function setPath(obj, value, props) {
for(var i = 0; i < props.length - 1; i++) {
if (props[i] in obj) {
obj = obj[props[i]];
} else {
return; // not found
}
}
obj[props[i]] = value;
}
alert(getPath(options, names)); // 15
setPath(options, 25, names);
alert(getPath(options, names)); // 25
这篇关于通过属性名称数组访问嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文