{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
这是我的 JSON 字符串。现在我想在此 JSON 中搜索名称,然后显示结果...
遍历键:
(增强阿米特·古普塔的答案)
var result = [];
getNames(data, "name");
document.write("result: " + result.join(", "));
function getNames(obj, name) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if ("object" == typeof(obj[key])) {
getNames(obj[key], name);
} else if (key == name) {
result.push(obj[key]);
}
}
}
}
工作演示@http://jsfiddle.net/rorkules/JFEMH/
const data = {
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}
let result = [];
getNames(data, "title");
document.write("result: " + result.join(", "));
function getNames(obj, name) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if ("object" == typeof(obj[key])) {
getNames(obj[key], name);
} else if (key == name) {
result.push(obj[key]);
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)