javascript - JSON filtering attributes - Stack Overflow

What is the best way to filter JSON nested keys and delete them? For example:{ "id": &quo

What is the best way to filter JSON nested keys and delete them? For example:

{ "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
    }
  ]
}

To get the following JSON by deleting all key1 and key2 items recursively:

{ "id"    : "1",
  "name"  : "someone",
  "age"   : 39,
  "data"  : [
    { "id"    : "1234",
      "name"  : "someone",
      "age"   : 39
    },
    { "id"    : "1234",
      "name"  : "someone",
      "age"   : 39
    }
  ] 
}

Thanks.

What is the best way to filter JSON nested keys and delete them? For example:

{ "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
    }
  ]
}

To get the following JSON by deleting all key1 and key2 items recursively:

{ "id"    : "1",
  "name"  : "someone",
  "age"   : 39,
  "data"  : [
    { "id"    : "1234",
      "name"  : "someone",
      "age"   : 39
    },
    { "id"    : "1234",
      "name"  : "someone",
      "age"   : 39
    }
  ] 
}

Thanks.

Share Improve this question edited Sep 26, 2011 at 23:46 Jordan Running 106k18 gold badges188 silver badges187 bronze badges asked Sep 26, 2011 at 23:31 JautomatorJautomator 1491 silver badge9 bronze badges 1
  • Check your curly braces, you have syntax errors in there – mrk Commented Sep 26, 2011 at 23:43
Add a ment  | 

3 Answers 3

Reset to default 5

Something like this should work:

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);
                }
            }
        }         
    }
}

Fiddle here

Assuming this is the JSON for an object called, say, people, something like this should work:

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);

Note:

Object.keys() and Array.forEach() aren't available in Internet Explorer < 9. Happily MDC provides working polyfills for both: Object.keys(), Array.forEach().

Your question contains your answer: recursively!

Your base cases are the "primitive" JSON types: strings and numbers. These remain unchanged. For arrays, you apply the operation to each element of the array, returning a new array.

The interesting case is objects. Here, for each key-value pair, you apply the operation to each value (but ignore those whose key is one you would like to "delete") and write them into a new object.

As an (off the cuff) example, using 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!
    }
};

If you want to remove more than one key, adjust the second parameter and condition in the recursive case as you see fit.

NOTE This is a non-destructive, which may or may not be what you need; the other answer (by Vivin Paliath) has a destructive version.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745366812a4624618.html

相关推荐

  • javascript - JSON filtering attributes - Stack Overflow

    What is the best way to filter JSON nested keys and delete them? For example:{ "id": &quo

    9小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信