Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - delete object from JSON array [duplicate]

I would like to delete an object from a JSON objects array. Here is the array:

var standardRatingArray = [
    { "Q": "Meal",
      "type": "stars"
    },
    { "Q": "Drinks",
      "type": "stars"
    },
    { "Q": "Cleanliness",
      "type": "stars"
    }
];

For example how can I delete the object whose key is "Q": "Drinks" ? Preferably of course without iterating the array.

Thanks in advance.

like image 860
David Faizulaev Avatar asked Dec 05 '25 14:12

David Faizulaev


1 Answers

You have to find the index of the item to remove, so you'll always have to iterate the array, at least partially. In ES6, I would do it like this:

const standardRatingArray = [
    { "Q": "Meal",
      "type": "stars"
    },
    { "Q": "Drinks",
      "type": "stars"
    },
    { "Q": "Cleanliness",
      "type": "stars"
    }
];

const index = standardRatingArray.findIndex(x => x.Q === "Drinks");

if (index !== undefined) standardRatingArray.splice(index, 1);

console.log("After removal:", standardRatingArray);
like image 128
CRice Avatar answered Dec 08 '25 04:12

CRice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!