JSON获取键/值:如果不存在,JS就停止了。如何解决方法来设置数组?

时间:2013-02-08 23:39:55

标签: javascript jquery json

鉴于localStorage中的大型JSON表和用户提供的给定密钥,我访问了一个关联的值。但是如果值和/或键不存在,那么我想创建它们。然而...

鉴于以下JSON:

var data = [ 
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 1 },
{ 'myKey': 'C' },
{ 'myKey': 'D', 'status': 1 }
];

以下JS:

function getJsonVal(json, itemId) {
    for (var i in json) {
        if (json[i].myKey == itemId) {
            return json[i]; 
        }
    }
}

如果我......

// request non-existing-in-JSON value:
valC = getJsonVal(data, 'C');
alert("this is C's value: "+ valC)

// request non-existing-in-JSON key:
keyE = getJsonVal(data, 'E');
alert("this is E: "+ keyE);

剧本中途停止。

我希望有一些错误值允许我制作类似If ( null|| undefined ) Then create new key/value的内容,但我的脚本只是因为这些项目不存在而停止。任何解决方法? Jsfiddle欣赏。

4 个答案:

答案 0 :(得分:1)

使用typeof运算符,您可以安全地检查属性是否已设置

function getJsonVal(json, itemId) {
    for (var i in json) {
        if (typeof json[i].myKey != 'undefined' && json[i].myKey == itemId) {
            return json[i]; 
        }
    }
    return 'someDefault';
}

答案 1 :(得分:1)

我对您的示例代码的修订:

http://jsfiddle.net/dqLWP/

var data = [ 
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 1 },
{ 'myKey': 'C' },
{ 'myKey': 'D', 'status': 1 }
];

function getJsonVal(json, itemId) {
    for (var i in json) {
        if (json[i].myKey == itemId) {
            return json[i]; 
        }
    }
}

var output = getJsonVal(data, 'E');
alert("this is the outputted value: "+ output);

if ( ! output) {
    alert('time to create that new key/value you wanted');
}

答案 2 :(得分:0)

除非您在某处设置变量CE的值,否则需要将它们放在引号中:

// request non-existing-in-JSON value:
valC = getJsonVal(data, 'C');
alert("this is C's value: "+ valC)

// request non-existing-in-JSON key:
keyE = getJsonVal(data, 'E');
alert("this is E: "+ keyE);

此外,您应该提醒您设置的变量(valCkeyE)。

答案 3 :(得分:0)

改善Lyndon的答案:

function getJsonVal(json, itemId) {
    for (var i in json) {
        if (json[i].myKey == itemId) {
            return json[i].status; // add .status here so you can see the value of keys that exist and have one.
        }
    }
}