我可以随机面对三种类型的 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")
对于第一个,创建一个空数组 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 - 在 JSON 中通过键和值查找对象,以防我不知道 JSON 的结构是单个、数组还是嵌套深层结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59703427/