鉴于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欣赏。
答案 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)
我对您的示例代码的修订:
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)
除非您在某处设置变量C
和E
的值,否则需要将它们放在引号中:
// 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);
此外,您应该提醒您设置的变量(valC
或keyE
)。
答案 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.
}
}
}