Javascript 使用字符串访问 JSON 或 JS 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7027051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:18:48  来源:igfitidea点击:

Access JSON or JS property using string

javascriptjson

提问by jagdipa

I have a JSON array like this:

我有一个像这样的 JSON 数组:

_htaItems = [
    {"ID":1,
     "parentColumnSortID":"0",
     "description":"Precondition",
     "columnSortID":"1",
     "itemType":0},
    {"ID":2,
     "parentColumnSortID":"0",
     "description":"Precondition",
     "columnSortID":"1",
    "itemType":0}]

I want to update this by passing the ID, column name and new value to a function:

我想通过将 ID、列名和新值传递给函数来更新它:

    function updateJSON(ID, columnName, newValue)
    {
        var i = 0;
        for (i = 0; i < _htaItems.length; i++)
        {
            if (_htaItems[i].ID == ID)
            {
                ?????
            }
        }
    }  

My question is, how do I update the value? I know I can do something like the following:

我的问题是,如何更新值?我知道我可以执行以下操作:

 _htaItems[x].description = 'New Value'

But in my cause, the column name is being passed as a string.

但在我的原因中,列名作为字符串传递。

回答by T.J. Crowder

In JavaScript, you can access an object property either with literal notation:

在 JavaScript 中,您可以使用文字符号访问对象属性:

the.answer = 42;

Or with bracketed notation using a string for the property name:

或者使用带有属性名称的字符串的括号表示法:

the["answer"] = 42;

Those two statements do exactlythe same thing, but in the case of the second one, since what goes in the brackets is a string, it can be any expression that resolves to a string (or can be coerced to one). So all of these do the same thing:

这两个语句完全相同,但在第二个语句的情况下,由于括号中的内容是字符串,因此它可以是解析为字符串的任何表达式(或可以强制为字符串)。所以所有这些都做同样的事情:

x = "answer";
the[x] = 42;

x = "ans";
y = "wer";
the[x + y] = 42;

function foo() {
    return "answer";
}
the[foo()] = 42;

...which is to set the answerproperty of the object theto 42.

...这是answer将对象的属性设置the42.

So if descriptionin your example can't be a literal because it's being passed to you from somewhere else, you can use bracketed notation:

因此,如果description在您的示例中不能是文字,因为它是从其他地方传递给您的,您可以使用方括号表示法:

s = "description";
_htaItems[x][s] = 'New Value';

回答by sternr

_htaItems[x][columnName] = 'New Value'; Or did I misunderstand you?

_htaItems[x][columnName] = '新值'; 还是我误会了你?

回答by JAAulde

You need to use square bracket notation, just like you did for array index:

您需要使用方括号表示法,就像您对数组索引所做的一样:

_htaItems[i][columnName] = newValue;

回答by Digital Plane

Just do _htaItems[i][columnName] = newValue;. It will change the property specified in columnNameto newValue.

就做_htaItems[i][columnName] = newValue;。它将改变中指定的属性columnNamenewValue