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

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

当前回答

演示对象示例

let obj = {
    name: {
        first_name: "Bugs",
        last_name: "Founder",
        role: "Programmer"
    }
}

的值的虚线字符串键

let key = "name.first_name"

函数

const getValueByDottedKeys = (obj, strKey)=>{
    let keys = strKey.split(".")
    let value = obj[keys[0]];   
    for(let i=1;i<keys.length;i++){
        value = value[keys[i]]
    }
    return value
}

调用getValueByDottedKeys函数

value = getValueByDottedKeys(obj, key)
console.log(value)

输出

Bugs

const getValueByDottedKeys = (obj, strKey)=>{ 让键= strKey.split(".") Let value = obj[keys[0]]; (让我= 1,< keys.length;我+ +){ Value = Value [key [i]] } 返回值 } 让obj = { 名称:{ first_name:“虫子”, last_name:“创始人”, 作用:“程序员” } } Let key = "name.first_name" value = getValueByDottedKeys(obj, key) console.log(值)

其他回答

你可以像这样使用Lodash get

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

我问了一个类似于这个主题的问题,经过大量的研究,看到了很多应该在这里丢失的信息,我觉得我有一些有价值的东西可以添加到这篇旧文章中。

首先,我想说明有几种方法来获取属性的值并将其存储在动态变量中。第一个最受欢迎,也是最简单的方法是:

let properyValue = element.style['enter-a-property'];

然而,我很少走这条路,因为它不工作的属性值通过样式表分配。为了给您一个示例,我将使用一些伪代码进行演示。

 let elem = document.getElementById('someDiv');
 let cssProp = elem.style['width'];

Using the code example above; if the width property of the div element that was stored in the 'elem' variable was styled in a CSS style-sheet, and not styled inside of its HTML tag, you are without a doubt going to get a return value of undefined stored inside of the cssProp variable. The undefined value occurs because in-order to get the correct value, the code written inside a CSS Style-Sheet needs to be computed in-order to get the value, therefore; you must use a method that will compute the value of the property who's value lies within the style-sheet.

因此,getComputedStyle()方法!

function getCssProp(){
  let ele = document.getElementById("test");
  let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}

这提供了一个很好的例子,并让您可以使用它,然而,这个链接Mozilla CSS getComputedValue文档详细讨论了getComputedValue函数,任何有抱负的开发人员如果对这个主题不完全清楚,都应该阅读。

顺便说一句,getComputedValue方法只获取,不设置。这显然是一个主要的缺点,但是有一个方法可以从CSS样式表中获取,以及设置值,尽管它不是标准的Javascript。 JQuery方法…

$(selector).css(property,value)

...是get,是set。这就是我所使用的,唯一的缺点是你必须了解JQuery,但这是每个Javascript开发人员都应该学习JQuery的许多很好的理由之一,它只是让生活变得简单,并提供了一些方法,就像这个,这在标准Javascript中是不可用的。 希望这能帮助到一些人!!

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

干杯!

有两种方法访问对象的属性:

点符号:something.bar 括号符号:something['bar']

括号之间的值可以是任何表达式。因此,如果属性名称存储在变量中,则必须使用括号表示:

Var something = { 栏:“foo” }; Var foo = 'bar'; //两者x = something[foo]和something[foo] = x正常工作 console.log ((foo)); console.log (something.bar)

在javascript中,我们可以访问:

点表示法- foo.bar 方括号- foo[someVar]或foo["string"]

但是只有第二种情况允许动态访问属性:

var foo = { pName1 : 1, pName2 : [1, {foo : bar }, 3] , ...}

var name = "pName"
var num  = 1;

foo[name + num]; // 1

// -- 

var a = 2;
var b = 1;
var c = "foo";

foo[name + a][b][c]; // bar