在JavaScript中,JSON的过滤级别递归地保留子对象是通过使用递归函数来实现的。递归函数可以遍历JSON对象的所有属性,并根据过滤条件来保留或排除子对象。
以下是一个示例代码,演示如何递归地保留JSON对象中符合条件的子对象:
function filterJSON(json, filter) {
if (typeof json !== 'object') {
return json;
}
if (Array.isArray(json)) {
return json.map(item => filterJSON(item, filter));
}
const result = {};
for (let key in json) {
if (json.hasOwnProperty(key)) {
const value = json[key];
if (filter(key, value)) {
result[key] = filterJSON(value, filter);
}
}
}
return result;
}
在上述代码中,filterJSON
函数接受两个参数:json
表示要过滤的JSON对象,filter
表示过滤条件的回调函数。回调函数接受两个参数:key
表示当前属性的键名,value
表示当前属性的值。回调函数应返回一个布尔值,指示是否保留该子对象。
使用示例:
const json = {
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
}
};
const filteredJSON = filterJSON(json, (key, value) => {
// 保留所有子对象
return typeof value === 'object';
});
console.log(filteredJSON);
输出结果:
{
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
}
}
在这个例子中,我们使用filterJSON
函数过滤了JSON对象,只保留了所有子对象。你可以根据自己的需求修改回调函数来实现不同的过滤逻辑。
腾讯云相关产品和产品介绍链接地址:
请注意,以上产品仅作为示例,实际选择产品应根据具体需求和情况进行评估。
领取专属 10元无门槛券
手把手带您无忧上云