gpt4 book ai didi

javascript - 在 JSON 中搜索对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:54:06 25 4
gpt4 key购买 nike

{"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 中搜索名称,然后显示结果...

最佳答案

遍历键:(增强 Amit Gupta 的回答)

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/roberkules/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]);
}
}
}
}

关于javascript - 在 JSON 中搜索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6110327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com