使用字符串访问JSON或JS属性 [英] Access JSON or JS property using string

查看:127
本文介绍了使用字符串访问JSON或JS属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JSON array like this:

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

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

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

    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.

推荐答案

在JavaScript中,您可以使用文字表示法访问对象属性:

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

the.answer = 42;

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

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

the["answer"] = 42;

这两个陈述完全相同的东西,但是在第二个,因为括号中的内容是一个字符串,它可以是任何解析为字符串的表达式(或者可以强制转换为一个字符串)。所以这些都做同样的事情:

Those two statements do exactly the 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;

...这是设置答案对象的属性 42

...which is to set the answer property of the object the to 42.

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

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

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

这篇关于使用字符串访问JSON或JS属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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