JSON过滤属性
JSON filtering attributes
过滤JSON嵌套键并删除它们的最佳方法是什么?例如:
{ "id" : "1",
"key1" : "val1",
"key2" : "val2",
"name" : "someone",
"age" : 39,
"data" : [
{ "id" : "1234",
"key1" : "val1",
"key2" : "val2",
"name" : "someone",
"age" : 39
},
{ "id" : "1234",
"key1" : "val1",
"key2" : "val2",
"name" : "someone",
"age" : 39
}
]
}
通过递归删除所有key1
和key2
项来获得以下JSON:
{ "id" : "1",
"name" : "someone",
"age" : 39,
"data" : [
{ "id" : "1234",
"name" : "someone",
"age" : 39
},
{ "id" : "1234",
"name" : "someone",
"age" : 39
}
]
}
谢谢。
应该这样做:
function deleteRecursive(data, key) {
for(var property in data) {
if(data.hasOwnProperty(property)) {
if(property == key) {
delete data[key];
}
else {
if(typeof data[property] === "object") {
deleteRecursive(data[property], key);
}
}
}
}
}
这里的小提琴
假设这是一个对象的JSON,比如,people
,像这样的东西应该工作:
function objWithoutPropsIDontLike(obj, propsIDontLike) {
// check to make sure the given parameter is an object
if(typeof obj == "object" && obj !== null) { // typeof null gives "object" ಠ_ಠ
// for every property name... (see note on Object.keys() and
// Array.forEach() below)
obj.keys().forEach(function(prop) {
// Test if the property name is one of the ones you don't like
// (Array.indexOf() returns -1 if the item isn't found in the array).
if(propsIDontLike.indexOf(prop) >= 0) {
// if it is, nuke it
delete obj[prop];
} else if(obj[prop]) {
// if it isn't, recursively filter it
obj[prop] = filterPropsIDontLike(obj[prop], propsIDontLike);
}
});
}
// There is no else { ... }; if the thing given for "obj" isn't an object
// just return it as-is.
return obj;
}
var propsIDontLike = [ 'key1', 'key2' ];
people = objWithoutPropsIDontLike(people, propsIDontLike);
注意:
Object.keys()
和Array.forEach()
在Internet Explorer中不可用<9. 令人高兴的是,MDC为Object.keys(), Array.forEach()提供了工作的多边形。
你的问题包含了你的答案:递归!
基本情况是"原始"JSON类型:字符串和数字。这些保持不变。对于数组,将该操作应用于数组的每个元素,返回一个新数组。
有趣的例子是对象。这里,对于每个键-值对,您将操作应用于每个值(但忽略那些键是您想要"删除"的键的值),并将它们写入新对象。
作为一个(即兴)示例,使用jQuery:var removeKey(object, key){
if(typeof(object)==='number' || typeof(object)==='string'){
return object;
}
else if(typeof(object)==='object'){
var newObject = {};
$.each(object, function(k, value) {
if(k!==key){
newObject[k] = removeKey(value, key);
}
});
return newObject;
}
else {
// Oh dear, that wasn't really JSON!
}
};
如果要删除多个键,请根据需要调整递归情况下的第二个参数和条件。
这是一个非破坏性的,可能是也可能不是你需要的;另一个答案(Vivin Paliath)有一个破坏性的版本。
相关文章:
- 如何在Leaflet.js中按属性过滤TopoJSON功能
- Knockoutjs 模板:在通过某些属性过滤该数组后,如何将 1 个对象数组用于 2 个 DOM 元素
- 按对象属性过滤对象的角度
- Angularjs ng-repeat按一个属性过滤,属性重复问题
- ng重复 按深层属性过滤
- 培根.js如何基于另一个属性过滤事件流
- jQuery - 使用类属性过滤
- 按对象的属性过滤对象的 JavaScript 数组并删除重复项
- Knockout-通过多个对象属性过滤可观测阵列中的对象
- 在Angularjs应用程序中,使用嵌套对象属性过滤ng repeat不起作用
- 如何通过按钮数据属性过滤JSON文件
- 通过数组中对象内的对象属性过滤对象数组
- 基于JavaScript中嵌套的属性过滤出数组
- js查询模型通过集合属性过滤
- 如何在node.js中使用属性过滤Json数据?
- 根据data-*属性过滤选择选项
- 在Angularjs中通过对象属性过滤
- Ng-repeat -通过对象's常量属性过滤出不同的值
- 用外部的ng-repeat's object属性过滤嵌套的ng-repeat
- 如何在JavaScript中高效地合并两个对象数组,并按属性过滤重复项