我试图使用动态名称访问对象的属性。这可能吗?

const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"

当前回答

ES5 //检查深嵌套变量

这段简单的代码可以检查嵌套深度的变量/值是否存在,而不需要检查每个变量…

var getValue = function( s, context ){
    return Function.call( context || null, 'return ' + s )();
}

Ex. -嵌套很深的对象数组:

a = [ 
    {
      b : [
          {
             a : 1,
             b : [
                 {
                    c : 1,
                    d : 2   // we want to check for this
                 }
             ]
           }
      ]
    } 
]

而不是:

if(a && a[0] && a[0].b && a[0].b[0] && a[0].b[0].b && a[0].b[0].b[0] && a[0].b[0].b[0].d && a[0].b[0].b[0].d == 2 )  // true

我们现在可以:

if( getValue('a[0].b[0].b[0].d') == 2 ) // true

干杯!

其他回答

您应该使用JSON。解析,看看https://www.w3schools.com/js/js_json_parse.asp

const obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')
console.log(obj.name)
console.log(obj.age)

你可以在Javascript中使用getter

getter文档

检查对象内部是否存在有问题的属性, 如果它不存在,就从窗口拿走

const something = {
    get: (n) => this.n || something.n || window[n]
};

您可以使用括号符号动态访问对象的属性。这看起来像obj[yourKey],然而JavaScript对象并不是为动态更新或读取而设计的。它们打算在初始化时定义。

如果你想动态分配和访问键值对,你应该使用映射。

const yourKey = 'yourKey'; //初始化它的值 const map1 = new Map([ (“yourKey”、“yourValue”) ]); //初始化为空,然后动态赋值 const map2 = new Map(); map2。集(yourKey yourValue); console.log (map1.get (yourKey)); console.log (map2.get (yourKey));

通过引用查找对象,字符串, 注意,确保你传递的对象是克隆的,我使用cloneDeep从lodash

如果对象看起来像

const obj = {data: ['an Object',{person: {name: {first:'nick', last:'gray'} }]

路径看起来像这样

const objectPath = ['data',1,'person',name','last']

然后调用下面的方法,它将按给定的路径返回子对象

const child = findObjectByPath(obj, objectPath)
alert( child) // alerts "last"


const findObjectByPath = (objectIn: any, path: any[]) => {
    let obj = objectIn
    for (let i = 0; i <= path.length - 1; i++) {
        const item = path[i]
        // keep going up to the next parent
        obj = obj[item] // this is by reference
    }
    return obj
}

我也遇到了同样的问题,但是lodash模块在处理嵌套属性时受到了限制。我按照递归后代解析器的思想编写了一个更通用的解决方案。该解决方案适用于以下要点:

递归下降对象解引用