remove an offspring item from an array assembly

I have a variable called today that stores data retrieved from an API. I'm attempting to delete some information from it using a function, but I keep encountering the error message

Cannot read property 'id' of undefined.

SAMPLE DATA

[
    {
        "id":324,
        "firstName":"Chris",
        "lastName":"Jake",
        "orders":[
            {
                "id":162,
                "meals":[
                    {
                        "id":27,
                        "name":"French Fries",
                        "description":"test"
                    },
                    {
                        "id":28,
                        "name":"Plain Rice, Beans and Fish",
                        "description":"test"
                    }
                ],
                "serveDate":"2019-07-16 00:00:00"
            }
        ]
    }
]

DELETE FUNCTION

delete() {
    for (let r = 0; r < this.today.length; r++) {
        if (this.today[r].orders[r].id === this.orderId) {
            this.today.splice(r, 1);
        }
    }
}

Answer №1

The element "serverDate" is included in the array but does not have an id, which results in this error. If order[r].id is undefined, it will return false.

  delete() {
      for (let r = 0; r < this.today.length; r++) {
            if (this.today[r].orders[r].id && 
                this.today[r].orders[r].id ===   this.orderId) {
                this.today.splice(r, 1);
            }
      }
  }

Answer №2

Consider attempting it in the following manner:

 removeOrder() {
    this.today.forEach((element, index) => {
      element.orders.forEach((orderItem, subIndex) => {
        if (orderItem.id == this.orderId) {
          this.today[index].orders.splice(subIndex, 1);
        }
      })
    })
  }

Answer №3

I have a different perspective compared to the previous answer. "serverDate does not belong to the orders array as a whole, but rather it is a part of the first object within the orders array. Your issue lies in the structure of your for loop. Let's break down what is happening during each iteration:

for (let r = 0; r < today.length; r++) {
    if (today[r].orders[r].id === this.orderId) {
        today.splice(r, 1);
    }
}

//r == 0
today[r].orders[r].id === this.orderId //accesses the 0th element of the today array and the 0th element of the orders array

//r == 1
today[r].orders[r].id === this.orderId //accesses the 1st element of the today array and the 1st element of the orders array

//!! the remaining orders in today[0] and the order at index today[1].order[0] are being skipped!!

To avoid this issue, you should consider using nested for loops.

for (let r = 0; r < today.length; r++) { 
    for (let s=0 ; s < today[r].orders.length; s++) { 
        if (today[r].orders[s].id===this.orderId) { 
            //perform operations on either r or s depending on the context
        }
    }
}

Answer №4

When working with Angular services, you may receive a JSON object that needs to be manipulated. Here's an example of how you can remove specific data:

const data =  `[{
    "id":324,
    "firstName":"Chris",
    "lastName":"Jake",
    "orders":[
        {
            "id":162,
            "meals":[
                {
                    "id":27,
                    "name":"French Fries",
                    "description":"test"
                },
                {
                    "id":28,
                    "name":"Plain Rice, Beans and Fish",
                    "description":"test"
                }
            ],
            "serveDate":"2019-07-16 00:00:00"
        }
    ]
}]`;

let parse = JSON.parse(data); console.log(parse);

const orderid = 27;
console.log(parse[0].orders[0].meals);
for(let i = 0; i < parse[0].orders[0].meals.length; i++ ) {
    if(parse[0].orders[0].meals[i].id == orderid) {
        parse[0].orders[0].meals.splice(i, 1)
    }
}
console.log(parse)

If you're dealing with HTTP endpoints, there are more efficient ways to handle the data. Define your interfaces as follows:

Meal Interface

export interface meal{
    id: num | string;
    name: string;
    description: string
}

Order Interface

export interface order{
    id: num | string;
    meals: meal[];
    serveDate: string;
}

Data Interface

export interface data {
    id: num|string;
    firstname: string;
    lastname: string;
    orders: order[];
} 

In your service: this.http.get(this.dataurl)

You can navigate through your JSON model after subscribing as shown below:

this.http.get<data[]>(this.dataurl).subscribe(result => {
    if(result != null) {
        for(let u of result)
        {
            for(let o of u.orders)
            {
                for(let m of o.meals)
                {
                    if(orderid === m.id)
                    {
                     //remove your item from array
                    }
                }
            }
        }
    }
});

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

Using AngularJS to Extract JSON Data from a Table in an HTML Document

In the context of angularjs: I have a table with 2 fixed columns (ID & Comment) and additional columns that are added dynamically by the user clicking a button. The user can input data into the rows of this table, and I need to extract/ read this data. H ...

Is there a way for me to collaborate on a footer control with a different website?

Is it possible to seamlessly incorporate a footer from one website into another? Ideally, I want the footer HTML (and styles) to be dynamically inserted into different web pages. The common workaround is using an iframe, but this causes navigation issues ...

Ways to implement the useEffect hook within a table component for retrieving data from the backend

I'm in the process of creating a table that displays the following information: Id quantity of books 1 XX 2 ... 3 ... ... ... The quantity of books will be retrieved from the backend using useEffect useEff ...

What could be causing the data in the data table to remain undeleted unless the page is manually refreshed

I am facing an issue with the delete button functionality. When I press the button, it successfully deletes the row but requires a page refresh to make the deleted row disappear. How can I resolve this problem and ensure that the row is deleted without the ...

using an external JavaScript function in the MongoDB shell

In my case, I have JavaScript functions that are stored in a JSON file: functions={} functions.a = function(){ return "returned" } I've come across tutorials suggesting that by importing this JSON file, I should be able to use these ...

How can the top height of a jquery dialog be reduced?

Just starting out with jquery, I've got a dialog box and I'm looking to decrease the height of this red image: https://i.sstatic.net/BuyQL.png Is there a way to do it? I've already made changes in the jquery-ui.css code, like so: .ui-dia ...

how to choose the :after pseudo-element with jQuery

Below are the codes I have tried. When this popup appears, I want to be able to close the entire popbox using the close button. CSS code .bigdiv{ display:none; background-color:#efefef; box-shadow: 10px 10px 10px 100000px rgba(0, 0, 0, 0.4); ...

Removing Form Fields Utilizing Javascript

Is it possible to create a unique function in Javascript that automatically removes a form field if it remains unfilled? <form id="myform"> <label for="q1" id="q1label">question 1</label> <input type="text" id="q1" name="q1"/> < ...

Button react-native press following textInput within scroll view aware of keyboard movements

I'm currently facing an issue where I have a TextInput and a button nested inside a KeyboardAwareScrollView. The goal is for the user to input some text and then tap the button created using TouchableOpacity, which should send the inputted text forwar ...

Experiencing CORS problem in Ionic 3 when accessing API on device

I am a newcomer to IONIC and I am utilizing a slim REST API with Ionic 3. Currently, I am encountering the following error: "Failed to load : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin&apos ...

What is the best way to dynamically assign an id to an ajax Actionlink in ASP.NET?

I have a collection of items and each item contains an Ajax.ActionLink. I would like to dynamically set the id for each action link based on the item's id. @Ajax.ActionLink("Join","ajaxview", new{id = tour.TourId}, new { HttpMethod = "GET", Insertion ...

Tips for automatically closing a dropdown menu when it loses focus

I'm having some trouble with my Tailwind CSS and jQuery setup. After trying a few different things, I can't seem to get it working quite right. In the code below, you'll see that I have placed a focusout event on the outer div containing th ...

In JavaScript, escape is comparable to android decode

I used a JavaScript method to encode a string: var result = escape('Вася') The resultant string is: "%u0412%u0430%u0441%u044F" Now I need to decode this string in Java. How can I achieve this? The following attempt did not work: URLDecod ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Tips for sending information to a child component from a parent in Vue.js

Is there a way to pass the image url to this vue component? I am moving the code to a separate php file that will contain the <script> tag used by Vue, but it seems like it won't recognize the passed data from a parent component. Vue.component( ...

Automatically submitting the form

Is there a way to automatically submit a form once 4 numbers are inputted into the field without having to press enter or click submit? <form action="send.php" method="POST"> <input type="number" maxlength="4"> </form> I have a basic ...

Unexpected character error occurs when using VSCode with Vue: ''‌'

Recently, I've encountered some strange errors while working on a Vuejs project in VSCode. Whenever I try to write arrow functions or use brackets, I get unexpected character errors. For example, if I insert an empty computed section between methods a ...

Implement a feature where users can add text inputs to specific columns in a table by

Recently, I've been diving into jquery table manipulation. I've written a code snippet that is supposed to add a text input field to a specific column when clicked. In my case, the column is the 9th. Here's the code I have so far: $('# ...

Unable to retrieve scripts upon returning to the main page of a Jquery website

Starting fresh with this post, I'm feeling incredibly frustrated and close to giving up on JQM completely. This shouldn't be so difficult. Here's my website structure: OUI/ index.php js/ pages/ images/ On the index.php page at http://loca ...

Angular 6 is showcasing dates in a quirky manner

In my Angular app, users can enter comments. The comments are displayed automatically with the date they were added. However, there is an odd behavior that I've noticed: When a user enters a comment, the time displayed is incorrect. (Check the ...