I have an array of json object and I cant pop an element javascript

remove element from array javascript
json array of objects
javascript array
remove first element from array javascript
javascript array shift
remove last element from array javascript
javascript array splice
javascript array push

Good day guys, I have an array of json in the first part of the program it would look like this:

var jsonToSaveToDB = [
        {
            ProductID: null,
            Quantity: null,
            TotalPrice: null
        }
    ];

Later on the program, I have a function that will populate that array with json and as a result, it would look like this:

var jsonToSaveToDB = [

  {
        ProductID: 1,
        Quantity: 4,
        TotalPrice: 12.80
    },
    {
        ProductID: 2,
        Quantity: 2,
        TotalPrice: 12.80
    },

    ..... other elements of the array

    {
        ProductID: null,
        Quantity: null,
        TotalPrice: null
    }
];

and I want to popup the last element of the array.Because, All the value of that last element was null.

But the catch is, I can't pop an element from that array. If you want to see my code structure.

It would look like this:

<script>
var jsonToSaveToDB = [
    {
        ProductID: null,
        Quantity: null,
        TotalPrice: null
    }
];

///some codes....
//....
$(document).ready(function(){

   function checkoutNow() {

        $.each(carted_prods, function (index, element) {
            var newObj = {
                ProductID: parseInt(element.itemID),
                Quantity: parseInt(element.itemQuantity),
                TotalPrice: parseFloat(element.itemPrice)
            };
            jsonToSaveToDB.unshift(newObj);
        });

        console.log(jsonToSaveToDB);

        if (jsonToSaveToDB.length > 0) {
            $.ajax({
                url: '/POS/POS/CheckoutProducts',
                data: { json: JSON.stringify(jsonToSaveToDB) },
                contentType: "application/json",
                success: function (result) {
                    console.log(result);
                }
            });
        }


        //console.log("Checkout now.");
    }

});

</script>

If the issue that you're facing in jsonToSaveToDB array is that you're always getting null values for ProductID, Quantity, TotalPrice in the last element of the array, you can easily remove them using jsonToSaveToDB.pop().

If you don't know where the position of the object element in the array jsonToSaveToDB, then you can filter them out from the array.

jsonToSaveToDB.filter(obj => obj.ProductID !== null)

I hope this helps. Let me know if you have any doubts.

Array.prototype.pop(), The pop() method removes the last element from an array and returns Objects which do not contain a length property reflecting the last in a� Most of the time when you are getting undefined, the object/array simply doesn't have a property with that name. const foo = {bar: {baz: 42}}; console.log(foo.baz); // undefined Use console.log or console.dir and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.

I would suggest not to initialise the array of object properties with null values at the beginning. Set initially

var jsonToSaveToDB =[] 

and

function checkoutNow() {
    $.each(carted_prods, function (index, element) {
        if(element.itemID || element.itemQuantity || element.itemPrice){
            var newObj = {
                ProductID: parseInt(element.itemID),
                Quantity: parseInt(element.itemQuantity),
                TotalPrice: parseFloat(element.itemPrice)
            };
            jsonToSaveToDB.unshift(newObj);
        }
   });
   ... Other codes
}

This code will add the contents in the array without the null object value. And add a check in the $.each loop

(if(element.itemID || element.itemQuantity || element.itemPrice))

That if any one value is present in the element, add it to the array. You can customise further according to the needs.Hope this helps.

JavaScript Array pop() Method, The pop() method removes the last element of an array, and returns that *An array item can be a string, a number, an array, a boolean, or any other object� On average I work with JSON data 18 times a week. And I still need to google for specific ways to manipulate them almost every time. What if there was an ultimate guide that could always give you the answer? In this article, I'll show you the basics of working with object arrays in JavaScript. If you ever worked with a JSON structure, you've worked with JavaScript objects. Quite literally

I already found an answer to my questions, the carted_prods variable was an array of json it contains an element with a null value which by the time that it goes to the $.each() it will populate a NaN so i use this code to filter out the element that doesn't have a null and NaN

 jsonToSaveToDB = jsonToSaveToDB.filter(obj => !isNaN(obj.ProductID));
 jsonToSaveToDB = jsonToSaveToDB.filter(obj => obj.ProductID != null)

JSON Arrays, In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined. Arrays in JSON Objects. The square brackets [ ] are used to declare JSON array. JSON array are ordered list of values. JSON array can store multiple value types. JSON array can store string, number, boolean, object or other array inside JSON array. In JSON array, values must be separated by comma. Arrays in JSON are almost the same as arrays in JavaScript.

5. Arrays, Objects, Functions and JSON, Typically when writing Javascript for execution on the client side you have to force Objects. You have the choice between using arrays or objects for storing your data in Arrays are ordered - the order in which you add items (e.g. push/ pop or forEach(callback[, thisObject]), Calls a function for each element in the array. hey thank u for your helping but i have the same problem , but with different code . this is my code m i add extra values in JSON Array . var J={ "myMenu

Using a Replacer or Filter with JSON.stringify, First we demonstrate applying a filter array to a JavaScript object. code comments) confirms that these properties have been preserved in the stringify result. In short, a replacer function can't be used to remove elements from an array but� Note the differences in accessing the values of an array vs an object. Convert PHP Array or Object to JSON String. PHP also features a json_encode function to convert an array or object into a string. Read more about the json_encode function from PHP’s documentation.

How to delete a value from an array in JavaScript, How do I remove an element from an array? Is the delete operator of any use? There also exists funny named splice() and slice() , what about those? I want to� I need to parse JSON response in key value pair Please note channel list– contain hashmap of channel name and its description so key value will differ on calls from one client to another client.

Comments
  • jsonToSaveToDB.pop() should work in you case. Please let me know what issue you are facing while using this.
  • the element is still there
  • I would suggest to create a stackblitz.com and put you code here, so we can figure out what is the issue with your code.
  • i have an NaN error I guess it was the carted_prods