通过属性名称的数组访问嵌套的对象 [英] Access nested objects via array of property names

查看:126
本文介绍了通过属性名称的数组访问嵌套的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这样的一个对象(简体):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆