首页 > 解决方案 > 如何使用字符串访问嵌套对象值以便我可以编辑?

问题描述

如果我有以下字符串或数组:

var thestring = '[0]["more"][0]["more"][0]["text"]';
var thearray = ['0','more','0','more','0','text'];

如何使用该字符串或数组来识别对象的一部分以便可以编辑它?

var theobject = [
    {
        "id":1,
        "text":"hello",
        "more": [
            {
                "id":2,
                "text":"hello",
                "more":[
                    {
                        "id":3,
                        "text":"hello", // I want to edit this
                        "more": [
                            {
                                "id":4,
                                "text":"hello",
                                "more":[
                                ]
                            }
                        ]
                    }
                ]
            }
         ]
    },
    {
        "id":5,
        "text":"hello"
    },
    {
        "id":6,
        "text":"hello"
    },
    {
        "id":7,
        "text":"hello"
    }
];

基本上我正在尝试访问对象的这一部分:

theobject[0]["more"][0]["more"][0]["text"];

但是如果我用一个字符串来做它就行不通了:

theobject[thestring];

标签: javascript

解决方案


查看 lodash _.get 和 _.set 函数,它们允许您使用路径类型语法访问对象,例如

_.get(object, 'property1.property2.property3', defaultValue);

存在等效的 _.set 函数,它们都很有用。

https://lodash.com/docs#get

https://lodash.com/docs#set

来自 lodash 文档:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');

_.get(object, ['a', '0', 'b', 'c']);

_.get(object, 'a.b.c', 'default');

提供默认对象的能力也很不错,它使访问深度下一个对象变得非常容易。

Set 以类似的方式工作:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4

_.set(object, ['x', '0', 'y', 'z'], 5);
console.log(object.x[0].y.z);
// => 5

推荐阅读