JSON过滤属性

JSON filtering attributes

本文关键字:属性 过滤 JSON      更新时间:2023-09-26

过滤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
    }
  ]
}

通过递归删除所有key1key2项来获得以下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)有一个破坏性的版本。