Search code examples
javascriptarraysecmascript-6javascript-objects

Delete an object inside an array of objects by value


Having the following nested array of objects:

[
    {
        "items": [
            {
                "name": "See data",
                "href": "/data",
            },
            {
                "name": "Account",
                "href": "/account",
                "icon": {}
            }
        ]
    },
    {
        "items": [
            {
                "name": "name",
                "href": "/name",
                "icon": {}
            },
            {
                "name": "My Rooms",
                "href": "/rooms",
                "icon": {}
            }
        ]
    },
    {
        "items": [
            {
                "name": "user",
                "href": "/user",
                "icon": {}
            }
        ]
    }
]

How it's possible to remove an inside object by name?

For example to remove the object with name "Account"?

A solution that works is delete myData[0].items[1]; but it's kind of hardcoded.

Also tried like:

myData[0].items = myData[0].items.filter(function (item) {
  return item.name !== 'Account';
});

Solution

  • You can use splice to change the original array in-place and findIndex to find the index of the item to remove.

    for (const {items} of data) {
        const i = items.findIndex(({name}) => name === 'Account');
        if (i > -1) items.splice(i, 1);
    }