4

I have an array that looks like the following:

[
    {
        "id": "denuzi",
        "sub":
        [
            {"id": "s4p58o"},
            {"id": "xzbqi"},
        ],
    },
    {
        "id": "4rcodm",
        "sub": [],
    }
]

What I am trying to do is remove an item from the array or from a nested array using a provided id.

e.g. if denuzi is provided then the entire first object is removed; if s4p58o is provided just that object from the first objects sub array is removed.

I know that I can remove an entire object with the following code:

_.remove(this.items, function(item) {
    return item.id !== id;
});

But I am not sure how to make a check to remove a sub item?

2 Answers 2

4

You could take an iterative and recursive approach by checking the id or call again for sub. Exit if found.

function remove(array, id) {
    return array.some((o, i, a) => o.id === id
        ? a.splice(i, 1)
        : remove(o.sub || [], id)
    );
}

var array = [{ id: "denuzi", sub: [{ id: "s4p58o" }, { id: "xzbqi" }] }, { id: "4rcodm", sub: [] }];

remove(array, 's4p58o');
console.log(array);

remove(array, 'denuzi');
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

-3

Just use Array.prototype.filter

var list = [
    {
        "id": "denuzi",
        "sub":
        [
            {"id": "s4p58o"},
            {"id": "xzbqi"},
        ],
    },
    {
        "id": "4rcodm",
        "sub": [],
    }
]

const result = list.filter(a => a.id !== 'denuzi');

console.log(result);

1 Comment

It doesn't work for nested structure, for example, you s4p58o can't be removed with your solution.

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.