javascript - 如果我不知道 JSON 的结构是单个、数组或嵌套的深层结构,请在 JSON 中通过键和值查找对象
问题描述
我可以随机面对三种类型的 JSON,
拳种、对象:
{ "a" : "b", "@type" : "Product" }
第二种类型,数组:
[{ "a" : "b", "@type" : "Test" }, { "a" : "b", "@type" : "Product" }]
第三种,嵌套对象:
{ "d" : "e", "f" : { "a" : "b", "@type" : "Product" } }
我正在尝试获取包含“@type”:“Product”的对象,因此我想要[{ "a" : "b", "@type" : "Product" }]
的结果将适用于所有类型。
为了得到这个结果,如果是第二个,我可以使用obj.filter(d => d["@type"]=="Product")
and 作为第一个,创建一个空数组,var empty_array = []; empty_array.push(obj)
然后使用与第二个相同的过滤器。
但是,当属性位于嵌套对象中时,我不知道如何获得所需的结果。
是否有任何 JSON 过滤器可以为所有类型获得所需的结果?
当我使用 JsonPath 时,我$..[?(@["\x40type"] =="Product"
在 Json 中进行了深度搜索,并且效果很好,但是我想在 Javascript 本身中找到方法。
提前谢谢了 :)
解决方案
你能试试下面的方法吗
// This method will return the type of object. In case of array or JSON, it will return array or json instead of object.
function getType(obj) {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
return 'array';
}
return 'json';
}
return typeof obj;
}
// This method will return either the required JSON or null.
function getObject(obj) {
// Check the type if it is JSON.
if (getType(obj) === 'json') {
// If the current object has a key named @type, return the object.
if (Object.keys(obj).includes('@type') && obj['@type'] === 'Product') return obj;
// Otherise call the method recursively for each value of JSON.
const values = Object.values(obj);
for (let i = 0, n = values.length; i < n; ++i) {
const returnVal = getObject(values[i]);
// If the value is required JSON, return that value.
if (returnVal) return returnVal;
}
// Check if the type of object is array.
} else if (getType(obj) === 'array') {
// Call the function recursively for each value of the array.
for (let i = 0, n = obj.length; i < n; ++i) {
const returnVal = getObject(obj[i]);
// If you get the required JSON, return it.
if (returnVal) return returnVal;
}
}
// If you didn't get the required JSON, return null.
return null;
}
var a = { "a" : "b", "@type" : "Product" };
var b = [{ "a" : "b", "@type" : "Test" }, { "a" : "b", "@type" : "Product" }];
var c = { "d" : "e", "f" : { "a" : "b", "@type" : "Product" } };
console.log(getObject(a));
console.log(getObject(b));
console.log(getObject(c));
推荐阅读
- javascript - 如何在 iframe 背景上拖放 javascript?
- r - 使用 lubridate 包在 r 中创建 inteval 对象
- swift - Swift 4 迁移
- python - 通过 html 中的 python 更新特定单元格
- python - python ctypes 垃圾回收
- mongodb - spark 连接到 mongoDB 分片集群,但没有获取数据
- ajax - 无法将ajax数据插入数据库codeigniter
- kubernetes - 如何在 Istio VirtualService 正则表达式中实现逻辑 OR?
- c# - 场景变化时如何运行一些代码?
- html - 网站宽度总是大于页面