以点表示法转换字符串以获取对象引用 [英] Convert string in dot notation to get the object reference

查看:125
本文介绍了以点表示法转换字符串以获取对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中考虑此对象,

Consider this object in javascript,

var obj = { a : { b: 1, c: 2 } };

给定字符串obj.ab如何获取此引用的对象,以便我可能改变它的价值?即我希望能够做类似的事情

given the string "obj.a.b" how can I get the object this refers to, so that I may alter its value? i.e. I want to be able to do something like

obj.a.b = 5;
obj.a.c = 10;

其中obj.a.b& obj.a.c是字符串(不是obj引用)。
我遇到了这篇文章我可以在哪里获得点符号字符串引用obj的值,但我需要的是一种可以获取对象本身的方法?

where "obj.a.b" & "obj.a.c" are strings (not obj references). I came across this post where I can get the value the dot notation string is referring to obj but what I need is a way I can get at the object itself?

对象的嵌套可能比这更深。即可能

The nesting of the object may be even deeper than this. i.e. maybe

var obj = { a: { b: 1, c : { d : 3, e : 4}, f: 5 } }


推荐答案

要获取该值,请考虑:

To obtain the value, consider:

function ref(obj, str) {
    str = str.split(".");
    for (var i = 0; i < str.length; i++)
        obj = obj[str[i]];
    return obj;
}

var obj = { a: { b: 1, c : { d : 3, e : 4}, f: 5 } }
str = 'a.c.d'
ref(obj, str) // 3

或以更奇特的方式,使用减少

or in a more fancy way, using reduce:

function ref(obj, str) {
    return str.split(".").reduce(function(o, x) { return o[x] }, obj);
}

在javascript中无法返回对象成员的可分配引用我必须使用如下函数:

Returning an assignable reference to an object member is not possible in javascript, you'll have to use a function like the following:

function set(obj, str, val) {
    str = str.split(".");
    while (str.length > 1)
        obj = obj[str.shift()];
    return obj[str.shift()] = val;
}

var obj = { a: { b: 1, c : { d : 3, e : 4}, f: 5 } }
str = 'a.c.d'
set(obj, str, 99)
console.log(obj.a.c.d) // 99

或使用上面给出的 ref 获取对包含对象的引用,然后应用 [] 运算符:

or use ref given above to obtain the reference to the containing object and then apply the [] operator to it:

parts = str.split(/\.(?=[^.]+$)/)  // Split "foo.bar.baz" into ["foo.bar", "baz"]
ref(obj, parts[0])[parts[1]] = 99

这篇关于以点表示法转换字符串以获取对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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