1

I know that there are a lot of similar questions, but no one the same. I have a quite complicated json tree:

"items": [
    {
    "slug": "level_1",
    "items": [
        { 
        "slug": "level_1_1"
        },
        {
        "slug": "level_1_2",
        "items": [
             {
             "slug": "level_1_2_1",
             },
             {
             "slug": "level_1_2_2"
             }
        ] 
        }
    ]},
    {
    "slug": "level_2"
    }
 ]

I need to have a function to delete/remove json element by "slug" value. Is it possible? I try everything that I found without success. I can use javascript/jQuery.

1 Answer 1

2

Process the tree recursively: you want a list consisting of the recursively-processed element, for each element that does not have a matching 'slug' value. The recursive processing consists of creating a new object, with the original slug and an 'items' list filtered by recursively calling the function.

Something like:

function my_filter(json_array, slug_to_remove) {
    return $.map(json_array, function(element) { 
        return (element.slug == slug_to_remove) ? null : {
            slug: element.slug, items: my_filter(element.items, slug_to_remove)
        };
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hello Karl! You dicover $.map for me! Thank you! In fact your solution have a mistake. If 'items' in child node will be null exception occurs. I update your solution: function my_filter(json_array, slug_to_remove) { return $.map(json_array, function (element) { return (element.slug == slug_to_remove) ? null : { slug: element.slug, items: (element.items == null) ? element.pages : my_filter(element.items, slug_to_remove) }; }); }
I didn't know there is an element.pages in your data, but I am happy you were able to make it work :)
oh sorry, I have use "pages" in real project instead of "items". It's a remark. =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.