gpt4 book ai didi

javascript - 使用 JQuery 中的字符串查找 JSON 对象中的键值

转载 作者:行者123 更新时间:2023-11-28 20:14:17 25 4
gpt4 key购买 nike

JSON 对象如下。需要根据用户输入找到该值。输入将类似于 "data.location.type""data.location.items[1].address.street"。可以在 JQuery 中完成吗?

{
"data": {
"location": {
"type": "List",
"count": 1,
"items": [
{
"id": 1,
"type": "S",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY"
}
},
{
"id": 2,
"type": "S",
"address": {
"street": "1323 South St",
"city": "New York",
"state": "NY"
}
}
]
}
}
}

最佳答案

首先,您需要将其解析为一个对象,然后使用如下所示的对象查找函数(这是一个实际操作的 fiddle http://jsfiddle.net/C8zH2/ ):

//https://gist.github.com/megawac/6162481#file-underscore-lookup-js
var lookup = function(obj, key) {
var type = typeof key;
if (type == 'string' || type == "number") key = ("" + key).replace(/\[(.*?)\]/, function(m, key){//handle case where [1] may occur
return '.' + key;
}).split('.');
for (var i = 0, l = key.length, currentkey; i < l; i++) {
if (obj.hasOwnProperty(key[i])) obj = obj[key[i]];
else return undefined;
}
return obj;
}

//syntax: lookup(jsonobj, input);
//Tests using your data
lookup(data, "data.location.type") //=> "List"
lookup(data, "data.location.items[1].address.street") //=> ""1323 South St"

关于javascript - 使用 JQuery 中的字符串查找 JSON 对象中的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19437205/

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