Remove an item from an array of objects based on its value

Within the array of nested objects provided below:

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

Is there a way to remove an object inside by specifying its name?

For instance, removing the object with the name "Account"?

One approach is delete myData[0].items[1]; but this method seems fixed.

Another attempt involved:

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

Answer №1

To modify the original array directly, you can utilize the splice method and findIndex to pinpoint the index of the item you want to remove.

for (const {elements} of information) {
    const index = elements.findIndex(({title}) => title === 'Task');
    if (index > -1) elements.splice(index, 1);
}

Answer №2

You should consider utilizing the map and filter methods for this task.

const myData= [
    {
        "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": {}
            }
        ]
    }
];


const removeByName = (data, targetName) => {
  return data.map(obj => ({
    ...obj,
    items: obj.items.filter(item => item.name !== targetName),
  }));
}

const updatedData = removeByName(myData, 'Account');

console.log(updatedData);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Exploring the challenges of implementing a jquerytools tooltip with AJAX

Currently, I have set up an ajax call to run every 15 seconds. The issue arises when the ajax call disables the tooltip if it's open at that moment for a particular item. This results in the destruction of only the tooltip being displayed, leaving oth ...

The functionality of the JavaScript array filter appears to be functioning properly; however, it does not display any output on

As the array (2001, 1999, 2000 and 2002) grows by 4 years The array is displayed on the screen, featuring the same 4 years It's determined that the highest year is 2002 2002 is then removed from the array The array is again shown on the screen with al ...

What is the best way to transfer the content from a tinyMCE textarea editor to an inner controller using Symfony3 and Ajax

I have two small rich text editors identified as #homepage and #thankyoupage. My goal is to submit the content of these TinyMCE text areas to a Symfony controller. Below is my front-end implementation: https://i.stack.imgur.com/TE1Ys.jpg Currently, I am ...

Incorporating external scripts into Angular HTML templates

I recently upgraded to a premium version of Polldaddy and received a script tag for embedding (without the correct id). <script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/0000000.js"></script> I am trying to loa ...

Error: The function of forEach is not applicable to todoList

_serilizedList(todoList){ let serialized = '*My to-dos:*\n'; todoList.forEach((t, i)=> { serialized += '*${i}* - ${t}\n'; }); return serialized; } Unexpected TypeError: todoList.forEach is not ...

Verify the presence and delete a table row from the JSON data that is returned

Is there a way to verify the presence of a label in the JSON response and exclude it from the displayed row in my table? In the code snippet below, you can observe that I am returning 'Page Name not defined'. I want to hide this label and any re ...

Increase the quantity with animation

I am attempting to increment a number within an element on the page. However, I require the number to have a comma included while the increment should only increase by 1 digit every second. The code is currently functional, but I am facing a dilemma regar ...

Struggling to retrieve a multidimensional array in C

In my current C project, I am tackling the challenge of writing a function that returns a pointer to an array. The elements within this array are pointers to initialized structures, each containing a pointer to another array. struct queueRecord; typedef s ...

As the height is expanded, the background color gradually infiltrates the body of the page

I am currently working on an angular application that utilizes angular-pdf. The controller and view function perfectly, and the PDF is displayed correctly, except for one issue. The height of the PDF exceeds the min-height of the module, causing it to expa ...

necessity for a condition in Material UI input field

I need assistance with a function that I use to incorporate Material UI text fields into my code. The issue I'm currently facing is figuring out how to dynamically add the "required" attribute based on a boolean parameter that determines whether the f ...

Ways to enhance a Vue component using slots

I am looking to enhance a third-party library component by adding an extra element and using it in the same way as before. For example: <third-party foo="bar" john="doe" propsFromOriginalLibrary="prop"> <template v ...

Changing the style of opening curly braces in JavaScript code styling

I have a piece of JavaScript code written for Vue that I would like to discuss. It is common practice in the JavaScript world to place the opening curly brace at the end of a line of code. <script> export default { name: 'newUser', data ...

javascript - developing a neutral constructor

Similar Question: Constructors in Javascript objects I am exploring the concept of creating classes in JavaScript. I am struggling to grasp it fully. Now, I am curious if it's possible to create a constructor in JavaScript, similar to what can b ...

Tips for preventing duplicate properties in Material UI when using React JS

Incorporating components from Material-UI, I have designed a form where the state of inputs is controlled by the parent component. However, I encountered an error stating "No duplicate props allowed" due to having multiple onChange parameters. Is there a w ...

Can the tooltip on c3 charts be modified dynamically?

Creating a c3 chart involves defining various properties, including a tooltip. Here is an example: generateData = () => { const x = randomNR(0, 100); const y = randomNR(0, 100); const together = x + y; return { data: { columns: [ ...

Serve the mobile version to mobile visitors and the desktop version to all other visitors

Can someone please explain to me how I can display the Mobile Version of a website when visiting on my phone, and the Desktop Version when viewing on anything larger than 500px? I have separately created both a Mobile Website and a Desktop Website. Is it ...

Ways to conceal a button using Javascript

Due to my limited JavaScript experience, I am struggling with understanding the event flow. This was written in haste, and further editing may be needed. I am working on creating a stack of cards (Bootstrap cards) along with a load button. To keep it inde ...

How do you typically approach testing Cloud Code on Parse?

While working on developing a substantial amount of business logic in webhooks like beforeSave/afterSave/etc. using Parse.com, I have encountered some challenges as a JavaScript/Parse beginner. The process seems somewhat tedious and I'm questioning if ...

Using getElementByID with dynamically generated IDs

I need to extract data from a website for my job using a Chrome bookmarklet. Unfortunately, I don't have permission to modify the site's code. Here's an example of the type of field I want to extract: <div style="width:100%; height:10 ...

Leverage the `dispatch` hook within a useEffect function

When it comes to triggering an action upon the React component unmounting, I faced a challenge due to hooks not allowing the use of componentWillUnmount. In order to address this, I turned to the useEffect hook: const dispatch = useDispatch(); useEffect(( ...