在Javascript中获取/设置对象深度属性的最佳方法是什么? [英] What is the best way to get/set an objects deep property in Javascript?

查看:103
本文介绍了在Javascript中获取/设置对象深度属性的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从对象获得更深层的属性是非常烦人的。如果父项不存在,则会出错。因此,当父母不存在时,您需要停止前往该房产。

It is notoriously annoying to get a deeper property from an object. If the parent does not exist, you get an error. So you need to stop getting to the property when a parent doesn't exist.

无能为力的方法是:

if (parent.value && parent.value.subvalue && parent.value.subvalue.targetvalue)
    var myVal = parent.value.subvalue.targetvalue;
else
    var myVal = null;

当您需要经常获得物业时,这是不可行的,您需要一个快捷功能。首先我做了这样的事情:

When you need to get a property often, this is unworkable and you need a shortcut function. First I did something like this:

function getProp(path) {
    try {
        return eval(path);
    }
    catch (e) {
        return null;
    }
};
// getProp('parent.value.subvalue.targetvalue');

但由于至少有两个原因,这是蹩脚的:对象必须在范围内,没有人喜欢使用 eval()

But this is lame for at least two reasons: The object must be in the scope, and no one likes to use eval().

所以也许将对象应用于函数更好:

So maybe it's better to apply the object to the function:

function getProp(path, parent) {
    path = path.split('.');

    var val = parent;

    for (var k = 0; k < path.length; k++) {
        var key = path[k];

        try {
            val = val[key];
        }
        catch (e) {
            return null;
        }
    }

    return val;
};
// getProp('value.subvalue.targetvalue', parent);

但不知怎的,它仍然感觉不对。

你好吗?这个?什么是最佳做法?

But somehow it still doesn't feel right.
How do you do this? What is best practice?

设置父对象可能存在或不存在的对象深度属性更加烦人。

Setting an objects deep property of which the parents may or may not exist is even more annoying.

parent = parent || {};
parent.value = parent.value || {};
parent.value.subvalue = parent.value.subvalue || {};
parent.value.subvalue.target = "YAY SOME VALUE!"

你会如何很好地解决这个问题?

How would you tackle this nicely?

是否还有javascript原生函数,因为这需要经常进行?

Are there javascript native functions for this yet, since this needs to be done often?

推荐答案

内置方式,没有。如果你在Node.js平台,你可以尝试一些软件包,如 dotty

Builtin ways, no. If you're in Node.js platform you can try some package like dotty.

无论如何,我认为你可以这样做的方式有点像这样(我没有测试过它!但我觉得它可行):

Anyway, the way I think you could do it is somewhat like this (I haven't tested it! But I think it could work):

key.split( "." ).reduce(function( memo, part ) {
   if ( typeof memo !== "object" || memo[ part ] === undefined ) {
      return;
   }

   return memo[ part ];
}, obj );

这篇关于在Javascript中获取/设置对象深度属性的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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