Sachin1392 Sachin1392 - 4 months ago 7
JSON Question

Remove the object or item which I have in the json string format from javascript array named data?

var item = {"mtyp":2,"mtr":3,"qnt":51,"unt":"pint","nts":"cvbbcv"}

var data = [{"mtyp":"2","mtr":"2","qnt":"54","unt":"ml","nts":"ngvjn"},{"mtyp":"2","mtr":"3","qnt":"51","unt":"pint","nts":"cvbbcv"}]


output should be:

var data = [{"mtyp":"2","mtr":"2","qnt":"54","unt":"ml","nts":"ngvjn"}]

Answer

You can use below script that I have written to meet your requirement. I am assuming that your JSON object will have similar key names at both end, if not then let me know I will update the script for you.

Your desired result will be available in resultdata.

<script type="text/javascript">
    var item = { "mtyp": 2, "mtr": 3, "qnt": 51, "unt": "pint", "nts": "cvbbcv" }

    var data = [{ "mtyp": "2", "mtr": "2", "qnt": "54", "unt": "ml", "nts": "ngvjn" }, { "mtyp": "2", "mtr": "3", "qnt": "51", "unt": "pint", "nts": "cvbbcv" }]

    // Holds the result data.
    var resultdata = [{}];

    // Remove initialized result set.
    resultdata.pop();

    // Variable to hold comparison value.
    var hasMatch = false;

    // Loop through data values.
    for (var index = 0; index < data.length; ++index) {

        // Fetch current item.
        var individualData = data[index];

        // Compare item values with individual data values.
        if (item.mtyp == individualData.mtyp &&
            item.mtr == individualData.mtr &&
            item.qnt == individualData.qnt &&
            item.unt == individualData.unt &&
            item.nts == individualData.nts) {
            hasMatch = true;
        }
        else {
            hasMatch = false;
        }

        // If then is no match then add to the result.
        // ResultData will hold all the values that are not present in item.
        if (!hasMatch)
        { resultdata.push(individualData); }
    }
</script>
Comments